Unitech/PM2 — pull request #665 by rlidwka (2014-08-29 11:39:43+00:00)
Title: Better Programmatic API

With this patch you can do something like:

```js
var pm2 = require('pm2')()
.on('error', console.error)
.on('log', console.log)
.on('connect', function() {
console.log('connected to pm2')
})
.on('disconnect', function() {
console.log('disconnected')
})

pm2.app('test')
.script('/tmp/test.js')
.instances(4)
.error_file('/tmp/test-err.log')
.out_file('/tmp/test-out.log')
.on('stdout', console.log)
.on('stderr', console.error)
.start()

pm2.app('test2')
.script('/tmp/test2.js')
.instances(1)
.start()

setTimeout(function() {
pm2.list(function(err, list) {
list.map(function(process) {
console.log('app %s, pid %s', process.name, process.pid)
})
})
}, 2000)
```

1. You don't need to start `pm2.connect()`. It can connect and disconnect automatically.
2. `pm2` is turned into class, which means in the future you can add a feature to connect to multiple pm2 servers (i.e. `new PM2(server1), new PM2(server2)`)
3. `pm2` is turned into eventemitter, which means you can listen on its logs as events for example. This doesn't really work, but it could be.

I just realized that it's very far from be ready to be pulled in (that wrapper around options is awful for example). I could improve that of course, but that's a huge work, and I'm not completely sure it'll be appreciated.

But if you try to improve programmatic api further, here are a few nice ideas to consider.