Node.js Start script or run command and handoff to OS (no waiting)

Sometimes you want to run something in the OS from your node code but you do not want to follow it or have a callback posted on your stack. The default for child_process spawning is to hold on to a handle and park a callback on the stack. however there is an option which is called detached.

var spawn = require('child_process').spawn;
spawn('/usr/scripts/', ['param1'], {
    detached: true

You can even setup the environment of the call to add stdio and stderr pipes to the call and connect them to OS fs descriptors like this:

var fs = require('fs'),
    spawn = require('child_process').spawn,
    out = fs.openSync('./out.log', 'a'),
    err = fs.openSync('./err.log', 'a');

spawn('/usr/scripts/', ['param1'], {
    stdio: [ 'ignore', out, err ], // piping stdout and stderr to out.log
    detached: true

The unref disconnects the process. from the parent it equates to a disown in shell.

Thanks to O/P :

Also Ref:


nJoy 😉

Leave a Reply

Your email address will not be published. Required fields are marked *