Skip to content

Instantly share code, notes, and snippets.

@lambtron
Last active August 29, 2015 14:11
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 lambtron/5e9843af011b28913cd2 to your computer and use it in GitHub Desktop.
Save lambtron/5e9843af011b28913cd2 to your computer and use it in GitHub Desktop.
Read from json input file and output to another file as csv.
/**
* Module dependencies.
*/
var readline = require('readline');
var stream = require('stream');
var fs = require('fs');
/**
* Get file, read arguments from command line.
*/
function main() {
var input = process.argv.slice(2);
var output = process.argv.slice(3);
if (input.length === 0 || output.length === 0)
throw 'Try node /path/to/input/file.json /path/to/output/file.csv';
jsonfileToCsv(input, output);
}
/**
* Takes JSON string and writes it to CSV file.
*
* @param {String} input
* @param {String} output
*/
function jsonfileToCsv(input, output) {
var readStream = fs.createReadStream(input);
var writeStream = new stream;
var rl = readline.createInterface(readStream, writeStream);
rl.on('line', function(line) {
var object = JSON.parse(line);
var csv = objToCsv(object).slice(0, -1) + '\n';
fs.appendFile(output, csv, function (err) {
if (err) console.log(err);
});
});
rl.on('close', function() {
console.log('Reached eof');
process.exit(0);
});
}
/**
* Takes a Javascript Object and turns it into a csv line.
*
* @param {Object} obj
*
* @return {String}
*/
function objToCsv(obj) {
if (obj === null) return 'null,';
if (Object.keys(obj).length === 0) return ',';
var csv = '';
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof obj[prop] === 'object')
csv += objToCsv(obj[prop]);
else
csv += obj[prop] + ',';
}
}
return csv;
}
/**
* Start.
*/
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment