Skip to content

Instantly share code, notes, and snippets.

@dustinsmith1024
Created October 16, 2017 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinsmith1024/b7c072ef7fc05cc677ab955dbe122830 to your computer and use it in GitHub Desktop.
Save dustinsmith1024/b7c072ef7fc05cc677ab955dbe122830 to your computer and use it in GitHub Desktop.
▶ c2fo WM-292 ✗ node test-csv.js test.csv
test.csv
[ { header1: '1-1', header2: '1-2', header3: '1-3' },
{ header1: '2-1', header2: '2-2', header3: '2-3' },
{ header1: '3-1', header2: '3-2', header3: '3-3' } ]
▶ c2fo WM-292 ✗ node
> let val1 = false;
undefined
> t = require('./test-csv')
{ newTable: [Function: newTable] }
> h = t.newTable('test.csv', function(data) {console.log("D", data[0]); val1 = data[0].header1; })
test.csv
undefined
> D { header1: '1-1', header2: '1-2', header3: '1-3' }
> val1
'1-1'
>
const fastCsv = require('fast-csv');
const fs = require('fs');
const csv = require('fast-csv');
/**
* Call this like so: `node test-csv.js test.csv`
* `test-csv.js` is the path to your CSV file.
*
* @param {String} fileName
* @param {Function} callback
*/
function newTable(fileName, callback) {
console.log(fileName)
const stream = fs.createReadStream(fileName);
const table =[];
csv
.fromStream(stream, {headers : true}, {objectMode : true})
.on("data", function(row){
table.push(row);
})
.on("end", function() {
callback(table);
});
}
if (process.argv[2]) {
newTable(process.argv[2], function(data) {
console.log(data);
});
}
module.exports = {
newTable,
};
header1 header2 header3
1-1 1-2 1-3
2-1 2-2 2-3
3-1 3-2 3-3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment