Skip to content

Instantly share code, notes, and snippets.

@mavame
Last active December 6, 2023 21:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mavame/316e53b6db10830f759f3cd61028ac80 to your computer and use it in GitHub Desktop.
Save mavame/316e53b6db10830f759f3cd61028ac80 to your computer and use it in GitHub Desktop.
Write JSON file from csv using Node.js
// 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