how to detach spawned child process in a node js script

how to detach spawned child process in a node js script  using -'node.js'

Intent: call an external application with specified arguments, and exit script.

The following script does not work as it should:

 var cp = require('child_process');
 var MANFILE='ALengthyNodeManual.pdf';
 cp.spawn('gnome-open', ['\''+MANFILE+'\''], {detached: true});

Things tried: exec - does not detach. Many thanks in advance

asked Oct 19, 2015 by shegokar.anjeet
0 votes

2 Answers

0 votes

From node.js documentation:

By default, the parent will wait for the detached child to exit. To prevent the parent from waiting for a given child, use the child.unref() method, and the parent's event loop will not include the child in its reference count.

When using the detached option to start a long-running process, the process will not stay running in the background unless it is provided with a stdio configuration that is not connected to the parent. If the parent's stdio is inherited, the child will remain attached to the controlling terminal.

You need to modify your code something like this:

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

var cp = require('child_process');
var MANFILE='ALengthyNodeManual.pdf';
var child = cp.spawn('gnome-open', [MANFILE], { detached: true, stdio: [ 'ignore', out, err ] });
answered Oct 19, 2015 by deepak
0 votes

My solution to this problem:


require('./spawn.js')('node worker.js');


module.exports = function( command ) {
    require('child_process').fork('./spawner.js', [command]); 


    'start cmd.exe @cmd /k "' + process.argv[2] + '"', 
answered Oct 19, 2015 by balvant maurya