process 是一个全局对象,它提供有关当前 Node.js 进程的信息并对其进行控制。它是你与环境、命令行参数、I/O 流、生命周期和信号的接口。
读取环境变量
js
process..;
process..;
port = process.. || ;
process.env 是读取配置和密钥(在代码外设置)的标准方式 — 是十二因子配置的核心。
// node script.js --name=Ann
process.argv; // ["node", "/path/script.js", "--name=Ann"]
const args = process.argv.slice(2); // skip the first two
process.stdout.write("output\n"); // console.log writes here
process.stderr.write("error\n"); // console.error writes here
process.stdin.on("data", (chunk) => { /* read input */ });
process.exit(0); // exit with success code (1 = error)
process.exitCode = 1; // preferred: set code, let the process finish naturally
process.pid; // the process id
process.cwd(); // current working directory
process.uptime(); // seconds the process has run
process.on("SIGTERM", () => { /* clean up, then exit — e.g. on container stop */ });
process.on("SIGINT", () => { /* Ctrl+C */ });
process.on("uncaughtException", (err) => { log(err); process.exit(1); });
process.on("unhandledRejection", (reason) => { log(reason); });
监听 SIGTERM/SIGINT 是实现优雅关闭的方式(完成进行中的请求、在退出前关闭 DB 连接),而未捕获错误处理程序是最后的安全防网。
process.memoryUsage(); // heap stats (leak detection)
process.nextTick(cb); // schedule a callback before the next event-loop phase
process.platform; // "linux" | "darwin" | "win32"
process 是你的程序与其运行时环境的连接。
你持续使用它:通过 process.env 读取配置/密钥、处理 CLI 参数,以及 — 对于生产环境很重要 — 捕获用于优雅关闭和最后的错误处理程序的信号。
理解它对构建可配置、稳健、生产就绪的 Node 应用程序至关重要。