在Linux上同时执行多个npm自定义的命令,两个命令都是启动Node站点。并且在后台运行

"start-client": "cross-env NODE_ENV=production node ./server/index.js",
"start-api": "cross-env NODE_ENV=production node ./server/api/index.js",
"start-pro": "concurrently \"npm run start-client\"  \"npm run start-api\""

以上的npm run start-pro在linux上直接运行是可以跑起来的,但是关掉当前会话之后服务就存在了也就关闭了。

当我执行npm run start-pro &这个命令的时候,也正常的跑起来了,当我关闭会话之后,站点出现了503的错误,使用lsof -i:8080lsof -i:8686查看端口是否存在,发现8080的端口不存在,但是8686的后端端口还存在。然后就放弃了这种操作。

当我执行nohup npm run start-pro &这个命令的时候,在项目的根目录出现了nohup.output的文件,里面记录了错误:


> p2@0.1.0 start-pro /website/pgyer
> concurrently "npm run start-client"  "npm run start-api"

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: EBADF: bad file descriptor, read
    at Error (native)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! p2@0.1.0 start-pro: `concurrently "npm run start-client"  "npm run start-api"`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the p2@0.1.0 start-pro script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2018-07-18T00_30_14_968Z-debug.log

再次想办法,使用先执行nohup npm run start-api &提示成功!在执行nobup npm run start-client &也执行成功!

本人比较强迫症,在这里想问一下,如何能一条命令一下执行npm run start-apinpm run start-client有什么方法吗?
阅读 5k
3 个回答

对nodejs不熟悉,无法从nodejs的应用层面提供帮助,不过没有好的办法的话可以试试下面两种方案

  1. 写个shell脚本startup.sh,通过脚本来启动这两个服务

     #!/usr/bin/env bash
    
     nohup npm run start-api &
     nohup npm run start-client &
    

    这样执行 ./startup.sh 就一个命令启动两个服务了

  2. 推荐使用的方式是PM2来管理node进程,PM2负责了node进程的启动,停止以及运行时监控等。
//package.json

"script":{
    "start-client": "cross-env NODE_ENV=production node ./server/index.js",
    "start-api": "cross-env NODE_ENV=production node ./server/api/index.js",
    "start-all": "npm run start-client && npm run start-api"
}
npm run start-all

@熊丸子

我试了一下,添加了

 "start-all": "npm run start-client && npm run start-api"

执行了nohup npm run start-all &这个命令,查看nohup,out发现只能执行start-client的命令

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题