Skip to content

Instantly share code, notes, and snippets.

@ashishmadeti
Created November 11, 2019 13:09
Show Gist options
  • Save ashishmadeti/17e26dfe46d9ed1a808db6ce6829c5c4 to your computer and use it in GitHub Desktop.
Save ashishmadeti/17e26dfe46d9ed1a808db6ce6829c5c4 to your computer and use it in GitHub Desktop.
Reading a CSV in Node.js
const readline = require('readline');
const fs = require('fs');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
// Consider the following CSV for the purpose of this example
// ID,Name
// 1.1,State Bank of India
// 1.2.1,K. L. Nair
// 1.2.2,Joyce Saldanha
// 1.3.1,Jagdish Singh
// 1.3.2,Neeta Singh
rl.question('', (path) => {
var file = fs.readFileSync(path, 'ascii');
var lines = file.split('\n');
for (var l = 1; l < lines.length; l++) {
var line = lines[l];
if (!line) {
continue; // Ignore any empty line
}
var data = line.split(','); // Split the row into component fields
console.log(data[0]); // Prints '1.1' in first iteration, '1.2.1' in second iteration and so on
console.log(data[1]); // Prints 'State Bank of India' in first iteration, 'K. L. Nair' in second iteration and so on
}
rl.close();
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment