Skip to content

Instantly share code, notes, and snippets.

@wuriyanto48
Last active November 15, 2023 06:36
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 wuriyanto48/2f0b31b9c97a536175ed19a410a678a4 to your computer and use it in GitHub Desktop.
Save wuriyanto48/2f0b31b9c97a536175ed19a410a678a4 to your computer and use it in GitHub Desktop.
convert JSON to .env file
const readline = require('readline');
const fs = require('fs');
const path = require('path');
// this function will convert json file to .env
// USAGE:
// => node ./scripts/json_to_env.js env.json
function main() {
const args = process.argv;
if (args.length <= 2) {
console.log('required json file argument');
process.exit(1);
}
const jsonFileArg = args[2];
const cwd = process.cwd();
const jsonPath = path.join(cwd, jsonFileArg);
if (!fs.existsSync(jsonPath)) {
console.log('json file does not exist');
process.exit(1);
}
const envOut = path.join(cwd, `${jsonFileArg}.env`);
try {
const outStream = fs.createWriteStream(envOut);
fs.readFile(jsonPath, (err, data) => {
if (err) {
console.log(err);
process.exit(1);
}
const jsonData = JSON.parse(data.toString('utf8'));
for (const k in jsonData) {
const line = `${k}=${jsonData[k]}`;
outStream.write(line);
outStream.write('\n');
}
outStream.end();
});
} catch(err) {
console.log(err);
process.exit(1);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment