在 Windows 上,可以使用以下命令将 Node.js 应用程序后台运行:

使用 Node.js 内置的 forever 模块:

  1. 首先,使用 npm 安装 forever 模块: npm install -g forever
  2. 然后,在应用程序的根目录中运行以下命令: forever start app.js

使用 PM2 进程管理器:

  1. 首先,使用 npm 安装 pm2 模块: npm install -g pm2
  2. 然后,在应用程序的根目录中运行以下命令: pm2 start app.js

使用 Windows 服务:

  1. 首先,安装 node-windows 模块: npm install -g node-windows
  2. 然后,在应用程序的根目录中运行以下命令: node-windows install --name 'MyApp' --script app.js
  3. 最后,使用以下命令启动服务: net start MyApp

注意: 在使用以上任何一种方法后台运行 Node.js 应用程序时,需要确保应用程序没有任何控制台输出。否则,应用程序将在后台运行时继续输出控制台信息,导致系统资源浪费。可以使用以下代码禁用控制台输出:

console.log = function() {}; // 禁用 console.log 输出

或者,在启动应用程序时添加 --silent 参数:

forever start app.js --silent

pm2 start app.js --silent
Windows 上 Node.js 后台运行方法详解

原文地址: https://www.cveoy.top/t/topic/gQfo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录