Windows 上 Node.js 后台运行方法详解
在 Windows 上,可以使用以下命令将 Node.js 应用程序后台运行:
使用 Node.js 内置的 forever 模块:
- 首先,使用 npm 安装 forever 模块:
npm install -g forever - 然后,在应用程序的根目录中运行以下命令:
forever start app.js
使用 PM2 进程管理器:
- 首先,使用 npm 安装 pm2 模块:
npm install -g pm2 - 然后,在应用程序的根目录中运行以下命令:
pm2 start app.js
使用 Windows 服务:
- 首先,安装 node-windows 模块:
npm install -g node-windows - 然后,在应用程序的根目录中运行以下命令:
node-windows install --name 'MyApp' --script app.js - 最后,使用以下命令启动服务:
net start MyApp
注意: 在使用以上任何一种方法后台运行 Node.js 应用程序时,需要确保应用程序没有任何控制台输出。否则,应用程序将在后台运行时继续输出控制台信息,导致系统资源浪费。可以使用以下代码禁用控制台输出:
console.log = function() {}; // 禁用 console.log 输出
或者,在启动应用程序时添加 --silent 参数:
forever start app.js --silent
pm2 start app.js --silent
原文地址: https://www.cveoy.top/t/topic/gQfo 著作权归作者所有。请勿转载和采集!