@hairy/lnv
Version:
Loading environment variables in Next.js and other frameworks can be quite cumbersome, and using dotenv or vault at runtime is also inconvenient. That's why my created this tool
52 lines (49 loc) • 1.43 kB
JavaScript
import {createRequire as __createRequire} from 'module';var require=__createRequire(import.meta.url);
// src/utils/index.ts
import fs from "node:fs";
import path from "node:path";
function parseCommandString(command) {
if (typeof command !== "string") {
throw new TypeError(`The command must be a string: ${String(command)}.`);
}
const trimmedCommand = command.trim();
if (trimmedCommand === "") {
return [];
}
const tokens = [];
for (const token of trimmedCommand.split(/ +/g)) {
const previousToken = tokens.at(-1);
if (previousToken && previousToken.endsWith("\\")) {
tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
} else {
tokens.push(token);
}
}
return tokens;
}
function replaceLiteralQuantity(input, parsed) {
return input.replace(/\$(\w+)/g, (_, key) => key in parsed ? parsed[key] : `$${key}`);
}
function readfiles(root, file, depth = false) {
let currentDir = root;
const files = [];
while (currentDir !== path.parse(currentDir).root) {
const envPath = path.join(currentDir, file);
if (fs.existsSync(envPath)) {
files.push(envPath);
if (!depth)
return files;
}
currentDir = path.dirname(currentDir);
}
return files;
}
function readfile(root, file, depth = false) {
return readfiles(root, file, depth)[0];
}
export {
parseCommandString,
replaceLiteralQuantity,
readfiles,
readfile
};