← 中文资源

简体中文版本

process.loadEnvFile 原生读取 .env

用 process.loadEnvFile() 原生加载 .env,无需第三方包;已存在的环境变量优先于文件值,文件缺失时抛出异常而非静默忽略。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

PORT = 4017LOG_LEVEL=debug
LOG_LEVEL after reload = info
missing file: ENOENT

实现说明

唯一的导入来源是 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);
}