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/script.sh', ['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/script.sh', ['param1'], {
    stdio: [ 'ignore', out, err ], // piping stdout and stderr to out.log
    detached: true
}).unref();

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

Thanks to O/P : https://stackoverflow.com/questions/25323703/nodejs-execute-command-in-background-and-forget

Also Ref: https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

and

https://github.com/nodejs/node-v0.x-archive/issues/9255

nJoy 😉

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.