由于这篇文章在过去几年里受到了很多关注,所以我在文章的底部列出了每个平台的最佳解决方案。


原来的帖子:

我希望我的node.js服务器在后台运行,即:当我关闭我的终端时,我希望我的服务器继续运行。我在谷歌上搜索过这个,并提出了这个教程,但它并不像预期的那样工作。因此,我没有使用这个守护进程脚本,我认为我只是使用了输出重定向(2>&1 >>文件部分),但这也不退出-我在终端中得到一个空行,就像它在等待输出/错误一样。

我也尝试过把进程放在后台,但是只要我关闭终端,进程就会被杀死。

那么,当我关闭本地计算机时,如何让它继续运行呢?


高级解决方案:

Systemd (Linux) Launchd (Mac) node-windows (Windows) PM2 (node . js)


当前回答

这个答案有点晚了,但是我发现最好的解决方案是编写一个同时使用screen -dmS和nohup命令的shell脚本。

screen -dmS newScreenName nohup node myserver.js >> logfile.log

我还在末尾添加了>>日志文件位,这样我就可以轻松地保存节点console.log()语句。

为什么我要使用shell脚本?我还添加了一个if语句,检查节点myserver.js进程是否已经在运行。

通过这种方式,我可以创建一个命令行选项,既可以让我保持服务器运行,也可以在我进行更改时重新启动服务器,这对开发非常有帮助。

其他回答

2017年6月更新: Linux解决方案:(Red hat)。之前的评论对我不起作用。 这适用于我的亚马逊网络服务-红帽7。希望这对外面的人有用。

A. Create the service file 
sudo vi /etc/systemd/system/myapp.service
[Unit]
Description=Your app
After=network.target

[Service]
ExecStart=/home/ec2-user/meantodos/start.sh
WorkingDirectory=/home/ec2-user/meantodos/

[Install]
WantedBy=multi-user.target

B. Create a shell file
/home/ec2-root/meantodos/start.sh
#!/bin/sh -
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to 8080
npm start

then:
chmod +rx /home/ec2-root/meantodos/start.sh
(to make this file executable)

C. Execute the Following

sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl status myapp

(If there are no errors, execute below.  Autorun after server restarted.)
chkconfig myapp -add

如果出于本地开发的目的,你需要启动多个NodeJS应用实例(express, fastify等),那么并发可能是一个选项。下面是一个设置:

先决条件

你的NodeJS应用(express, fastify等)被放置在/opt/mca/www/mca-backend/app路径下。 假设您使用的是通过brew install node@16安装的节点v.16

设置

Install concurrently: npm install -g concurrently Create a file ~/Library/LaunchAgents/mca.backend.plist <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>mca.backend</string> <key>LimitLoadToSessionType</key> <array> <string>Aqua</string> <string>Background</string> <string>LoginWindow</string> <string>StandardIO</string> <string>System</string> </array> <key>ProgramArguments</key> <array> <string>/usr/local/bin/concurrently</string> <string>--names</string> <string>dev,prd</string> <string>--success</string> <string>all</string> <string>--kill-others</string> <string>--no-color</string> <string>MCA_APP_STAGE=dev node ./server.mjs</string> <string>MCA_APP_STAGE=prod node ./server.mjs</string> </array> <key>RunAtLoad</key> <true/> <key>EnvironmentVariables</key> <dict> <key>PATH</key> <string>/usr/local/opt/node@16/bin:/usr/local/bin:/usr/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin</string> </dict> <key>WorkingDirectory</key> <string>/opt/mca/www/mca-backend/app</string> <key>StandardErrorPath</key> <string>/opt/mca/www/mca-backend/err.log</string> <key>StandardOutPath</key> <string>/opt/mca/www/mca-backend/out.log</string> </dict> </plist> Load and run: launchctl bootstrap gui/`id -u` $HOME/Library/LaunchAgents/mca.backend.plist Get a status: launchctl print gui/`id -u`/mca.backend Stop: launchctl kill SIGTERM gui/`id -u`/mca.backend Start/Restart: launchctl kickstart -k -p gui/`id -u`/mca.backend Unload if not needed anymore: launchctl bootout gui/`id -u`/mca.backend

重要提示:一旦你用launchctl加载service,引导你在文件中所做的任何更改 ~ /图书馆/ LaunchAgents / mca.backend。Plist将不会在行动,直到你卸载服务(通过使用launchctl bootout) 然后再次加载它(通过使用launchctl bootstrap)。

故障排除

查看启动日志:/private/var/log/com.apple.xpc.launchd/launchd.log

Node.js作为WINDOWS XP的后台服务

Hacksparrow在http://www.hacksparrow.com/install-node-js-and-npm-on-windows.html上提供了在windows下安装Node.js + npm的教程。 为了nnsm.exe的实现,荣誉归于Tatham Oddie: http://blog.tatham.oddie.com.au/2011/03/16/node-js-on-windows/。

安装:

Install WGET http://gnuwin32.sourceforge.net/packages/wget.htm via installer executable Install GIT http://code.google.com/p/msysgit/downloads/list via installer executable Install NSSM http://nssm.cc/download/?page=download via copying nnsm.exe into %windir%/system32 folder Create c:\node\helloworld.js // http://howtonode.org/hello-node var http = require('http'); var server = http.createServer(function (request, response) { response.writeHead(200, {"Content-Type": "text/plain"}); response.end("Hello World\n"); }); server.listen(8000); console.log("Server running at http://127.0.0.1:8000/"); Open command console and type the following (setx only if Resource Kit is installed) C:\node> set path=%PATH%;%CD% C:\node> setx path "%PATH%" C:\node> set NODE_PATH="C:\Program Files\nodejs\node_modules" C:\node> git config --system http.sslcainfo /bin/curl-ca-bundle.crt C:\node> git clone --recursive git://github.com/isaacs/npm.git C:\node> cd npm C:\node\npm> node cli.js install npm -gf C:\node> cd .. C:\node> nssm.exe install node-helloworld "C:\Program Files\nodejs\node.exe" c:\node\helloworld.js C:\node> net start node-helloworld A nifty batch goodie is to create c:\node\ServiceMe.cmd @echo off nssm.exe install node-%~n1 "C:\Program Files\nodejs\node.exe" %~s1 net start node-%~n1 pause

服务管理:

服务本身现在可以通过Start-> Run->访问 服务。msc或通过Start->运行-> MSCONFIG-> Services(并检查“隐藏” 所有微软服务)。 该脚本将为通过批处理脚本生成的每个节点加上前缀 “节点——”。 同样,它们可以在注册表中找到:"HKLM\SYSTEM\CurrentControlSet\Services\node-xxxx"

对于使用更新版本的守护进程npm模块的人,你需要传递文件描述符而不是字符串:

var fs = require('fs');
var stdoutFd = fs.openSync('output.log', 'a');
var stderrFd = fs.openSync('errors.log', 'a');
require('daemon')({
    stdout: stdoutFd, 
    stderr: stderrFd
});

使用NSSM的最佳解决方案为windows,只需下载NSSM,打开CMD到NSSM目录和类型

nssm install <service name> <node path> <app.js path> 

eg: nssm install myservice "C:\Program Files\nodejs" "C:\myapp\app.js" 

这将安装一个新的Windows服务,该服务将列在services中。您可以从那里启动或停止服务,该服务将自动启动,您可以配置为在失败时重新启动。