Sam
Sam

Reputation: 1229

Javascript Node Read from CSV file and store data into object

Trying to read a csv file and store data from it into an object which I can then use for other tasks.

    var csv = require('csv');

    var obj = csv();

    var filename = process.argv[2];

    function Employee(eno, ename, sal) {

        this.EmpNo = eno;
        this.EmpName = ename;
        this.Salary = sal;
    };

    var Employee = {};

    obj.from.path(filename).to.array(function (data) {
        for (var index = 0; index < data.length; index++) {
               Employees.push(new Employee(data[index][0], data[index][1], data[index][2]));
        }
    });

console.log(Employee);

When running this I get the error:

var obj = csv();
          ^

TypeError: csv is not a function

Any ideas?

Edit:

Changed to this as per answer below but cannot get the string to be populated outside the function:

string = {}

var lineReader = require('readline').createInterface({
    input: fs.createReadStream(filename)
});

lineReader.on('line', function (line) {
    var splitLine = line.split(',');

        string[splitLine[0]] = {
            name: splitLine[0],
            dob: splitLine[1],
            employeeid: splitLine[2],
            country: domain,
            zone: splitLine[4],
            type: splitLine[5],
            id: splitLine[7],
            number: splitLine[8]
        }

    lineReader.close()
    }
})

console.log(string)

Upvotes: 1

Views: 4092

Answers (1)

Alexander
Alexander

Reputation: 76

Looking at the documentation for the module, it looks like you're not quite using it correctly. csv is not a constructor, but instead has methods which you should call. There are some examples available which should guide you towards correct usage.

Callback example from the module website;

var csv = require('csv');

csv.generate({seed: 1, columns: 2, length: 20}, function(err, data){
  csv.parse(data, function(err, data){
    csv.transform(data, function(data){
      return data.map(function(value){return value.toUpperCase()});
    }, function(err, data){
      csv.stringify(data, function(err, data){
        process.stdout.write(data);
      });
    });
  });
});

If you want to read from a file, and append the contents to an array;

Input

name,age
Alex,24
Sam,99

Code

var fs = require('fs');
var csv = require('csv');
var strings = [];

var readStream = fs.createReadStream('./input.csv');

var parser = csv.parse({columns:true});

parser.on('readable', function() {
  while(record = parser.read()) {
    strings.push(record);
  }
});

parser.on('error', function(err) {
  console.log(err.message);
});

parser.on('finish', (function() {
  console.log(strings);
}));

readStream.pipe(parser);

Output

[ { name: 'Alex', age: '24' }, { name: 'Sam', age: '99' } ]

Upvotes: 4

Related Questions