Last active
August 15, 2017 23:46
-
-
Save pjho/7aba72708e5e09ef446e87efbe8f6f04 to your computer and use it in GitHub Desktop.
Node CSV to JSON
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// dependencies | |
// > yarn add csvtojson | |
// Usage: | |
// > node csv-to-json.js input.csv output.json | |
const fs = require('fs') | |
const path = require('path') | |
const csv = require('csvtojson') | |
const csvFile = path.resolve(process.argv[2]) | |
const jsonFile = path.resolve(process.argv[3]) | |
const output = [] | |
// do transformations and add to output array | |
function loadRow(row) { | |
output.push(row) | |
} | |
// write to file | |
function writeJson(err) { | |
if (err) { throw err } | |
const content = JSON.stringify(output, null, 2) | |
fs.writeFile(jsonFile, content, 'utf8', function (err) { | |
if (err) { throw err } | |
console.log(`Json file saved to ${jsonFile}`) | |
}) | |
} | |
// execute | |
csv() | |
.fromFile(csvFile) | |
.on('json', loadRow) | |
.on('done', writeJson) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment