NodeJS - reading and processing a delimiter separated file (csv) image

NodeJS – reading and processing a delimiter separated file (csv)

Frequently, there is a need to read data from a file, process it and route it onwards. In my case, the objective was to produce messages on a Kafka Topic. However, regardless of the objective, the basic steps of reading the file and processing its contents are required often. In this article I show the very basic steps with Node.js and and the Node module csv-parse.

1. npm init process-csv

Enter a small number of details in the command line dialog. Shown in blue:

image

2. npm install csv-parse -save

This will install Node module csv-parse. This module provides processing of delimiter separated files.

image

This also extends the generated file package.json with a reference to csv-parse:

image

3. Implement file processFile.js

The logic to read records from a csv file and do something (write to console) with each record is very straightforward. In this example, I will read data from the file countries2.csv, a file with records for all countries in the world (courtesy of https://restcountries.eu/)

image

The fields are semi colon separated, the records are each on a new line.

 

/*
This program reads and parses all lines from csv files countries2.csv into an array (countriesArray) of arrays; each nested array represents a country.
The initial file read is synchronous. The country records are kept in memory.
*/

var fs = require('fs');
var parse = require('csv-parse');

var inputFile='countries2.csv';
console.log("Processing Countries file");

var parser = parse({delimiter: ';'}, function (err, data) {
    // when all countries are available,then process them
    // note: array element at index 0 contains the row of headers that we should skip
    data.forEach(function(line) {
      // create country object out of parsed fields
      var country = { "name" : line[0]
                    , "code" : line[1]
                    , "continent" : line[2]
                    , "population" : line[4]
                    , "size" : line[5]
                    };
     console.log(JSON.stringify(country));
    });    
});

// read the inputFile, feed the contents to the parser
fs.createReadStream(inputFile).pipe(parser);

 

4. Run file with node procoessFile.js:

image

Tags:, , , ,

11 Comments

  1. Anjana May 19, 2020
  2. Franz Weber April 29, 2020
  3. Jon May 28, 2019
  4. Maxim Lyubitelev May 16, 2019
  5. Avengers May 13, 2019
    • Lucas Jellema May 13, 2019
  6. Vaibav September 11, 2018
  7. Dyego Cruz November 14, 2017
  8. alina July 10, 2017
    • Joe April 4, 2019
  9. faisal arkan June 12, 2017