如何通过PM2运行“ npm start”?

时间:2018-09-30 06:21:14

标签: node.js pm2

我在这里看到了很多问题,但这对我没有用。那为什么问这个问题?

我正在使用DigitalOcean Ubuntu 16.04服务器。我有一个由“ npm start”运行的节点项目。

脚本为:

"scripts": {    
    "start": "node ./bin/www"
}

通常pm2适用于

pm2 start app.js

由于我的脚本是这样的,并且由npm start运行,因此如何永远运行服务器。

3 个答案:

答案 0 :(得分:2)

您可以像这样内置npm脚本:

pm2 start npm -- start

如果您有自定义脚本,则可以这样运行:

pm2 start npm -- run custom

-

在您的情况下,pm2 start npm -- start将运行node ./bin/www。如果要运行start,请将node app.js脚本更改为node app.js

答案 1 :(得分:2)

npm start &&节点app.js有区别。这取决于项目的启动脚本。

对于您而言,上述答案是正确的,它将由pm2 start npm -- start运行。

但是如果它对您也不起作用(我不知道为什么它对您不起作用,请不要与我们分享任何错误),您可以更改启动脚本。

为此,您必须更改代码 您必须从bin/www文件中获取运行服务器的代码

示例:

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);


var server = http.createServer(app);



server.listen(port);
server.on('error', onError);
server.on('listening', onListening);



function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

以及您在www文件中编写的其他文件(用于运行服务器)必须移动app.js或主文件,然后可以尝试:

pm2 start app.js
or
forever start app.js

答案 2 :(得分:0)

是的,您可以优雅地使用 pm2 配置 (json) 文件非常高效地完成此操作。

package.json 文件(包含以下示例脚本)

"scripts": {
    "start": "concurrently npm:server npm:dev",
    "dev": "react-scripts start",
    "build": "node ./scripts/build.js",
    "eject": "react-scripts eject",
    "lint": "eslint src server",
    "shivkumarscript": "ts-node -T -P server/tsconfig.json server/index.ts"
  }

假设我们要使用 pm2 实用程序运行名为“shivkumarscript”的脚本。因此,我们的 pm2 配置文件应该如下所示,包含值为 'npm' 的 'script' 键和值为 'run' 的 'args' 键。在我们的例子中,脚本名称是“shivkumarscript”。

ecosystem.config.json 文件

module.exports = {
    apps: [
        {
            name: "NodeServer",
            script: "npm",
            automation: false,
            args: "run shivkumarscript",
            env: {
                NODE_ENV: "development"
            },
            env_production: {
                NODE_ENV: "production"
            }
        }
    ]
}

假设你已经在你的机器上安装了 Node.js、NPM 和 PM2。那么下面应该是通过 pm2 启动应用程序的命令,它将依次运行 npm 脚本(在应用程序的 package.json 文件中提到的命令行):

对于生产环境:

pm2 start ecosystem.config.js --env production --only NodeServer

对于开发环境:

pm2 start ecosystem.config.js --only NodeServer

...还有嘘!伙计们