Skip to content

Instantly share code, notes, and snippets.

@antony
Created June 6, 2023 15:00
Show Gist options
  • Save antony/492011ba6ce25149b312a3af070d857d to your computer and use it in GitHub Desktop.
Save antony/492011ba6ce25149b312a3af070d857d to your computer and use it in GitHub Desktop.
Convert from node-config to dotenv. Thanks ChatGPT!
'use strict'
const fs = require('fs')
const path = require('path')
const dotenv = require('dotenv')
const configDirPath = path.join(__dirname, './config')
const outputDirPath = path.join(__dirname, '.')
const toUpperSnakeCase = (str) => str.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase()
fs.readdir(configDirPath, (err, files) => {
if (err) {
console.error('Could not list the directory.', err)
process.exit(1)
}
files.forEach((file, index) => {
const configFilePath = path.join(configDirPath, file)
const outputFileName = file === 'default.js' ? '.env' : `.env.${file.split('.')[0]}`
const config = require(configFilePath)
let dotenvContent = ''
const envPath = path.join(outputDirPath, '.env')
let envConfig = {}
if (fs.existsSync(envPath)) {
envConfig = dotenv.parse(fs.readFileSync(envPath))
}
const configMap = new Map()
for (const key in envConfig) {
configMap.set(key, envConfig[key])
}
for (const key in config) {
const upperSnakeCaseKey = toUpperSnakeCase(key)
configMap.set(upperSnakeCaseKey, config[key])
}
configMap.forEach((value, key) => {
dotenvContent += `${key}=${value}\n`
})
fs.writeFileSync(path.join(outputDirPath, outputFileName), dotenvContent)
})
})
'use strict'
const fs = require('fs')
const path = require('path')
const replaceInFile = require('replace-in-file')
const srcDirPath = path.join(__dirname, './src')
const toUpperSnakeCase = (str) => str.replace(/([a-z])([A-Z])/g, '$1_$2').toUpperCase()
function fromDir (startPath, callback) {
if (!fs.existsSync(startPath)) {
console.log('no dir ', startPath)
return
}
const files = fs.readdirSync(startPath)
for (let i = 0; i < files.length; i++) {
const filename = path.join(startPath, files[i])
const stat = fs.lstatSync(filename)
if (stat.isDirectory()) {
fromDir(filename, callback)
} else if (filename.endsWith('.js') || filename.endsWith('.mjs') || filename.endsWith('.svelte')) {
callback(filename)
}
}
}
fromDir(srcDirPath, async function (filename) {
console.log('-- Found: ', filename)
try {
const regex = /process\.env\.([a-z][a-zA-Z]*)/g
const results = await replaceInFile({
files: filename,
from: regex,
to: (match) => {
const variableName = match.split('process.env.')[1]
return `process.env.${toUpperSnakeCase(variableName)}`
}
})
console.log('Replacement results:', results)
} catch (error) {
console.error('Error occurred:', error)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment