ihub-framework-js
Version:
Legacy version of iHub Framework written in Javascript
57 lines (44 loc) • 1.47 kB
JavaScript
const fs = require('fs');
const path = require('path');
const enviromentFilePath = path.join(process.cwd(), '.env');
const parse = (src) => {
const obj = {};
// convert Buffers before splitting into lines and processing
src.toString().split('\n').forEach((line) => {
// matching "KEY' and 'VAL' in 'KEY=VAL'
const keyValueArr = line.match(/^\s*([\w.-]+)\s*=\s*(.*)?\s*$/);
// matched?
if (keyValueArr != null) {
const key = keyValueArr[1];
// default undefined or missing values to empty string
let value = keyValueArr[2] || '';
// expand newlines in quoted values
const len = value ? value.length : 0;
if (len > 0 && value.charAt(0) === '"' && value.charAt(len - 1) === '"') {
value = value.replace(/\\n/gm, '\n');
}
// remove any surrounding quotes and extra spaces
value = value.replace(/(^['"]|['"]$)/g, '').trim();
// check if it's number
if (/^\d+$/.test(value)) {
value = parseInt(value, 10);
}
obj[key] = value;
}
});
return obj;
};
(() => {
// Checks if .env file exists
if (!fs.existsSync(enviromentFilePath)) return;
try {
const parsed = parse(fs.readFileSync(enviromentFilePath, 'utf8'));
Object.keys(parsed).forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
process.env[key] = parsed[key];
}
});
} catch (e) {
throw new Error(e);
}
})();