2

I need to count the lines of a CSV file. If the file is empty, I want to write the columns names as first line, then the info that I need to log.

Any suggestions how to do this?

junihh
  • 502
  • 1
  • 9
  • 25

2 Answers2

1
var i;
var count = 0;
require('fs').createReadStream(process.argv[2])
  .on('data', function(chunk) {
    for (i=0; i < chunk.length; ++i)
      if (chunk[i] == 10) count++;
  })
  .on('end', function() {
    console.log(count);
  });

This is a duplicate of Node.js: Count the number of lines in a file, please learn to google your problems first.

Community
  • 1
  • 1
isaac9A
  • 903
  • 4
  • 12
  • 30
0

Quick answer: To count the lines of a CSV file you can use this.

fs.readFile('mfile.csv', function (err, data) {
    if (!err) {
        let lines = null, data.toString().split('\n')
    }
})

Detailed answer: If the line count is 0, then you can write the header data such as column name.

fs.readFile('mfile.csv', function (err, data) {
    if (!err) {
        let lines = null, data.toString().split('\n')
        if(lines <= 0) {
           fs.writeFileSync('mfile.csv', 'cloumn name')
           console.log('added column name')
        }
        console.log('lines ' + lines)
    }
})
Googlian
  • 6,077
  • 3
  • 38
  • 44