diginext-utils
Version:
README.md
38 lines • 1.49 kB
JavaScript
import fs from "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.
*/
export default function parseEnvFile(path) {
const env = {};
// Check if the file exists
if (!fs.existsSync(path)) {
console.error("File not found");
return env;
}
// Read file contents
const fileContents = fs.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;
}
export { parseEnvFile };
//# sourceMappingURL=parseEnvFile.js.map