我在这里看到了很多问题,但这对我不起作用。那为什么问这个问题?
我正在使用 DigitalOcean Ubuntu 16.04 服务器。我有一个由“npm start”运行的节点项目。
脚本是:
"scripts": {
"start": "node ./bin/www"
}
一般 pm2 工作于
pm2 start app.js
由于我的脚本是这样的并由
npm start
运行,我怎样才能永远运行我的服务器。
您可以像这样运行内置的 npm 脚本:
pm2 start npm -- start
如果您有自定义脚本,可以像这样运行:
pm2 start npm -- run custom
--
在您的情况下,
pm2 start npm -- start
将运行node ./bin/www
。如果您想运行 start
,请将 node app.js
脚本更改为 node app.js
。
是的,您可以通过优雅地使用 pm2 配置(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”。
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
...还有轰隆隆!伙计们
我的应用程序称为“app.js”。我有一个与 Express Node.js 应用程序完全相同的启动脚本。
经过谷歌搜索后,这解决了我的问题,而不是调用 pm2 start app.js。
pm2 start ./bin/www
首先,您需要创建一个文件 run.js 并将以下代码粘贴到该文件上。
const { spawn } = require('child_process');
//here npm.cmd for windows.for others only use npm
const workerProcess = spawn('npm.cmd', ['start']);
workerProcess.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
workerProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
workerProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
并使用 pm2 运行此文件。
pm2 start run.js
您可以执行类似的操作,您可以将 Test Bot 替换为您想要的名称,然后 npm start 使用您想要的命令
pm2 start "npm start" --name "Test Bot"