编程
PM2 can be used programmatically, meaning that you can embed a process manager directly in your code, spawn processes, keep them alive even if the main script is exited.
Check out this article for more informations.
简单实例
This will require pm2, launch test.js
, list processes then exit the script.
You will notice that after exiting this script you will be able to see test.js
process with pm2 list
$ npm install pm2 --save
var pm2 = require('pm2');
// Connect or launch PM2
pm2.connect(function(err) {
// Start a script on the current folder
pm2.start('test.js', { name: 'test' }, function(err, proc) {
if (err) throw new Error('err');
// Get all processes running
pm2.list(function(err, process_list) {
console.log(process_list);
// Disconnect to PM2
pm2.disconnect(function() { process.exit(0) });
});
});
})
编程API
方法名 | API |
---|---|
Connect/Launch | pm2.connect(fn(err){}) |
Disconnect | pm2.disconnect(fn(err, proc){}) |
Consideration with .connect: the .connect method connect to the local PM2, but if PM2 is not up, it will launch it and will put in in background as you launched it via CLI.
方法名 | API |
---|---|
Start | pm2.start(script_path|json_path, options, fn(err, proc){}) |
Options | nodeArgs(arr), scriptArgs(arr), name(str), instances(int), error(str), output(str), pid(int), cron(str), mergeLogs(bool), watch(bool), runAsUser(int), runAsGroup(int), executeCommand(bool), interpreter(str), write(bool) |
Restart | pm2.restart(proc_name|proc_id|all, fn(err, proc){}) |
Stop | pm2.stop(proc_name|proc_id|all, fn(err, proc){}) |
Delete | pm2.delete(proc_name|proc_id|all, fn(err, proc){}) |
Reload | pm2.reload(proc_name|all, fn(err, proc){}) |
Graceful Reload | pm2.gracefulReload(proc_name|all, fn(err, proc){}) |
方法名 | API |
---|---|
List | pm2.list(fn(err, list){}) |
Describe process | pm2.describe(proc_name|proc_id, fn(err, list){}) |
Dump (save) | pm2.dump(fn(err, ret){}) |
Flush logs | pm2.flush(fn(err, ret){}) |
Reload logs | pm2.reloadLogs(fn(err, ret){}) |
Send signal | pm2.sendSignalToProcessName(signal,proc,fn(err, ret){}) |
Generate start script | pm2.startup(platform, fn(err, ret){}) |
Kill PM2 | pm2.killDaemon(fn(err, ret){}) |