Manage processes programmatically with PM2

by Alexandre Strzelewicz -

Since PM2 v0.9 the code has been refactored, and now it's much more modulable. We directly exposed PM2 CLI commands (command line interface) to a seamless API (application programming interface).

You can now embed a process management / code daemonization logic to your application with ease and use PM2 command directly from your code.

Simple example

You can access to the example here:

First, add PM2 to your package.json:

$ npm install pm2 --save

Then let's try this simple example that launch the test.js script:

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) {

      // Disconnect to PM2
      pm2.disconnect(function() { process.exit(0) });



Method name 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.

Method name API
Start pm2.start(script_path|json_path, options, fn(err, proc){})
Retart 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){})
Method name 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){})

For the next release we will automatically generate an API documentation from the current JSdoc comments.

Examples / More

If you encounter any problem or you have any questions, feel free to ask on the Github issue system

Hope it gonna be helpful to you to always conceive better softwares!

The Keymetrics team.

Start monitoring your application in less than a minute