Last active
December 6, 2023 21:53
-
-
Save mavame/316e53b6db10830f759f3cd61028ac80 to your computer and use it in GitHub Desktop.
Write JSON file from csv using Node.js
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
// given a csv file on the local filesystem, this program will JSON-serialize the contents in to a new file "output.json" | |
// First create a new directory and initialize a new node project: | |
// $ npm init -y && npm i -s csvtojson minimist | |
// Then run the program: | |
// $ node index.js -f path-to-csv.csv | |
const fs = require("fs"); | |
const csv = require("csvtojson/v2"); | |
const argv = require("minimist")(process.argv.slice(2)); | |
if (!argv || !argv.f) { | |
console.error("Please provide path to CSV file through the -f argument."); | |
process.exit(1); | |
} | |
csv().fromFile(argv.f) | |
.then(json => { | |
const file = "./output.json"; | |
fs.writeFileSync(file, JSON.stringify(json, null, 2), err => { | |
if (err) { | |
console.error(err); | |
} | |
console.log(`File written to ${file}.`); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment