diginext-utils
Version:
README.md
45 lines (44 loc) • 1.81 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseEnvFile = void 0;
const fs_1 = __importDefault(require("fs"));
/**
* Reads an .env file and converts it into a JavaScript object.
*
* @param {string} path - The path to the .env file.
* @return {Object} - An object with keys and values based on the .env file.
*/
function parseEnvFile(path) {
const env = {};
// Check if the file exists
if (!fs_1.default.existsSync(path)) {
console.error("File not found");
return env;
}
// Read file contents
const fileContents = fs_1.default.readFileSync(path, "utf8");
// Split the file content by new lines and iterate over each line
fileContents.split("\n").forEach((line) => {
// Trim whitespace and ignore comments or empty lines
const trimmedLine = line.trim();
if (trimmedLine.startsWith("#") || trimmedLine === "")
return;
// Split each line into key and value at the first '='
const [key, ...rest] = trimmedLine.split("=");
let value = rest.join("=").trim();
// Remove surrounding quotes if they wrap the entire value
if ((value.startsWith(`"`) && value.endsWith(`"`)) || (value.startsWith(`'`) && value.endsWith(`'`))) {
// Extract the value within the quotes, preserving any quotes that are part of the value
value = value.substring(1, value.length - 1);
}
// Add to env object
if (key)
env[key] = value;
});
return env;
}
exports.default = parseEnvFile;
exports.parseEnvFile = parseEnvFile;