且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在系统启动时启动 Node.js 应用程序?

更新时间:2023-10-11 16:47:28

如果您使用的是预构建的 Pi 版本,例如 0.10.24,您可能遇到 PATH 问题.

If you're using a prebuilt Pi release like 0.10.24, you may be experiencing a PATH issue.

您可以在 start 命令中提供节点二进制文件的完整路径,或者确保在 /etc/init.d/MyApp 之前设置节点二进制文件的 PATH 运行.我遇到了同样的问题,并成功地尝试了两者.此外,您拥有的 stop 命令可能无法正常工作.

You can either provide the full path to the node binary as part of the start command or make sure the PATH to the node binaries are set before /etc/init.d/MyApp is ran. I had the same issue and tried both with success. Also, the stop command as you have it may not be working.

#! /bin/sh
# /etc/init.d/test

### BEGIN INIT INFO
# Provides:          test
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d.
### END INIT INFO

# Carry out specific functions when asked to by the system
case "$1" in
   start)
    echo "Starting test.js"
    # run application you want to start
    #node /home/pi/test.js > /home/pi/test.log
    /home/pi/downloads/node-v0.10.24-linux-arm-pi/bin/node /home/pi/test.js >> /home/pi/test.log
   ;;
   stop)
    echo "Stopping test.js"
    # kill application you want to stop
    killall -9 node
    # Not a great approach for running
    # multiple node instances
    ;;
  *)
    echo "Usage: /etc/init.d/test {start|stop}"
    exit 1
    ;;
esac

exit 0

如果你想做 sudo node,你可以使用 sudo visudo 将 PATH 添加到 Defaults secure_path.

If you'd like to do sudo node, you can add the PATH to Defaults secure_path using sudo visudo.

此外,我建议使用类似 forever 之类的东西来让您的进程在崩溃后继续运行,而其他情况则不然.

Also, I would recommend using something like forever to keep your process running after crashes and what not.