实现说明
唯一的导入来源是 node:fs(Node.js 内建),暴露出 writeFileSync。
代码在启动时从环境读取 PORT、LOG_LEVEL。
使用要点
- 唯一的导入
node:fs属于 Node.js 标准库。 - 跑完文件,输出里会留下标记——
PORT =、LOG_LEVEL after reload =、missing file:。
常见问题
导入的模块是 npm 包吗?
不需要——node:fs 内置于 Node.js。node: 前缀就代表核心模块,项目里无需添加任何东西。
核心语句
writeFileSync('.env', 'PORT=4017\nLOG_LEVEL=debug\n');
process.loadEnvFile('missing.env');
process.env.LOG_LEVEL = 'info';
代码示例
import { writeFileSync } from 'node:fs';
// .env is the de-facto config format; Node loads it natively, no package
writeFileSync('.env', 'PORT=4017\nLOG_LEVEL=debug\n');
process.loadEnvFile();
console.log('PORT =', process.env.PORT);
// values already present in the environment win over the .env file
process.env.LOG_LEVEL = 'info';
writeFileSync('.env', 'PORT=4017\nLOG_LEVEL=debug\n');
process.loadEnvFile();
console.log('LOG_LEVEL after reload =', process.env.LOG_LEVEL);
// loadEnvFile throws when the file is missing, unlike reading env directly
try {
process.loadEnvFile('missing.env');
} catch (err) {
console.log('missing file:', err.code);
}