Skip to content

Instantly share code, notes, and snippets.

@a-tokyo
Created March 12, 2020 17:49
Show Gist options
  • Save a-tokyo/f86ad2f60e0d9b1d16affe28ff6cdbe7 to your computer and use it in GitHub Desktop.
Save a-tokyo/f86ad2f60e0d9b1d16affe28ff6cdbe7 to your computer and use it in GitHub Desktop.
Converts a .env file to a .env.js file
#!/usr/bin/env node
const fs = require('fs');
const path = require('path');
const os = require('os');
/**
* Writes bash env variables to a .env.js file
*/
// const _bashEnvToEnvFileJs = () => {
// /** Destination Env file path */
// const [filePath = '.env.js', includesStr] = process.argv.slice(2);
// /** Regexes to include */
// const includes = [
// 'NODE_ENV',
// '^REACT_APP_',
// ...includesStr ? includesStr.split(',') : [],
// ];
// /** Current env vars keys */
// const keys = Object.keys(process.env);
// /** Keys to include in the final file */
// const keysToInclude = [];
// /** Pick up the env var keys */
// for (let i = 0; i < keys.length; i++) {
// const key = keys[i];
// /** Check if key should be included */
// for (let j = 0; j < includes.length; j++) {
// const includeRegex = includes[j];
// if (key.match(includeRegex)) {
// /** Include key */
// keysToInclude.push(key);
// }
// }
// }
// /** Destination env file text */
// let fileText = ``;
// /** Build env vars */
// for (let i = 0; i < keysToInclude.length; i++) {
// fileText += `exports.${keysToInclude[i]} = '${process.env[keysToInclude[i]]}';\n`;
// }
// /** Write destination env file */
// fs.writeFileSync(path.resolve(filePath), fileText);
// };
/**
* Replicates a normal .env file to a .env.js file
*/
const _envFileToEnvFileJs = (
fromFilePath = '.env',
toFilePath = '.env.js',
) => {
const envFileText = fs.readFileSync(path.resolve(fromFilePath), 'utf8');
const envVars = envFileText
.trim()
.split(os.EOL)
.map(str => str.trim())
.filter(Boolean)
/* to JSON */
.reduce((prevValue, currentValue) => {
const delimiterIndex = currentValue.indexOf('='); // Gets the first index where an = occours
/* skip if comment or invalid line */
if (currentValue.startsWith('#') || delimiterIndex === -1) {
return prevValue;
}
const key = currentValue.substr(0, delimiterIndex); // Gets the first key
const value = currentValue.substr(delimiterIndex + 1); // Gets the value
/* skip if invalid line */
if (!key || !value) {
return prevValue;
}
/* Add new env var */
return {
...prevValue,
[key]: value,
};
}, {});
let fileText = ``;
/** Build env vars */
Object.keys(envVars).forEach(key => {
fileText += `exports.${key} = '${envVars[key]}';\n`;
});
fs.writeFileSync(path.resolve(toFilePath), fileText);
};
const main = () => {
_envFileToEnvFileJs();
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment