Last active
November 15, 2023 06:36
-
-
Save wuriyanto48/2f0b31b9c97a536175ed19a410a678a4 to your computer and use it in GitHub Desktop.
convert JSON to .env file
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
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