Skip to content

Instantly share code, notes, and snippets.

@pjho
Last active August 15, 2017 23:46
Show Gist options
  • Save pjho/7aba72708e5e09ef446e87efbe8f6f04 to your computer and use it in GitHub Desktop.
Save pjho/7aba72708e5e09ef446e87efbe8f6f04 to your computer and use it in GitHub Desktop.
Node CSV to JSON
// 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