user2700253
user2700253

Reputation: 21

how to get total number of records rows in a csv file using node.js

I have a csv file in local server.I am trying to get total number of rows in a csvfile at a time.But I am unable to do this.Please help.

Upvotes: 0

Views: 7044

Answers (2)

Nikhil S
Nikhil S

Reputation: 65

Used this snippet to calculate line count from Jason Kim's answer and it worked like a charm.

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function fileLineCount({ fileLocation }) {
  const { stdout } = await exec(`cat ${fileLocation} | wc -l`);
  return parseInt(stdout);
};

// Usage

async someFunction() {
  const lineCount = await fileLineCount({ fileLocation: 'some/file.json' });
}

P.S. This works for any type for file not just csv.

Upvotes: 1

Jim Mack
Jim Mack

Reputation: 1437

Work with CSV through a library, as Plato suggested.

FWIW, to get the length of any text file,

var content;
// First I want to read the file
fs.readFile('./local.csv', function read(err, data) {
    if (err) {
        throw err;
    }
    content = data;
    processFile();          // Or put the next step in a function and invoke it
});

function processFile() {
    lines = content.split("\r");   // look up
    rowCount = lines.length;
}

Upvotes: 0

Related Questions