0

Possible Duplicate:
node.js execute system command synchronously

I wish to synchronously execute a node.js file from another node.js file. This is what I have but its async.

    var spawn = spawn('node', ['./file.js']);
    spawn.stdout.on('data',function(data){});
Community
  • 1
  • 1
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424
  • You *really* want to do it synchronously? Rather than listening for the [`exit` event](http://nodejs.org/api/all.html#all_event_exit_2)? Because you seem to want to do something with the `stdout` from it. If you execute synchronously, that line won't run until the child is *done*... – T.J. Crowder Dec 06 '12 at 15:54
  • @T.J.Crowder I don't want a response, I don't want the server to wait for one either. I took `stdout` from another example in which I was waiting on `stdout`. Is there a better function that can do this, without installing a whole module? – ThomasReggi Dec 06 '12 at 16:19
  • @ThomasReggi: That sounds like you don't actually want it to be synchronous. I've added an answer that I hope will help. – T.J. Crowder Dec 06 '12 at 16:37

1 Answers1

2

From your comments under the question, it sounds like you don't want it to be synchronous, and that you don't care about its output.

If you just want to fire the other process and forget, without watching it or caring about when it ends, what you're already using (spawn) does that.

If you want to truly fire-and-forget, you'll want to specify the detached option, so that the child process doesn't get killed when your process terminates. From the docs:

If the detached option is set, the child process will be made the leader of a new process group. This makes it possible for the child to continue running after the parent exits.

Looking further down, apparently you have to unref it as well:

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.

And apparently deal with stdio:

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.

So:

spawn('node', ['./file.js'], {
    detached: true,
    stdio: [ 'ignore', 'ignore', 'ignore' ]
}).unref();
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875