11

I'm working with node.js and I want to when there's a request to a url like ./calculate start a new process to make these complex calculations, and I want that process to continue even if the script which called it has finished. Is it possible?

Thank you.

Mario
  • 1,841
  • 4
  • 16
  • 23

3 Answers3

5

You can use the natively provided child process facility: http://nodejs.org/api/child_process.html

And use the unix "nohup" command to keep the spawned process alive even if the parent process died.

Roman
  • 1,880
  • 1
  • 13
  • 12
  • Are you looking for the result of the child process work to be returned in the same connection that created it? – Roman Aug 10 '12 at 08:10
  • 1
    You can be smart about it and create a pool of child workers and communicate with them through a queue in the database (say using something like Redis), this can be very scalable and resilient. Few links that you might find useful: http://stackoverflow.com/questions/5630208/nodejs-child-processes-exec-can-not-return-nohup-command http://stackoverflow.com/questions/4762016/node-js-workers-background-processes – Roman Aug 10 '12 at 08:16
  • 1
    No, I just want to start the process, I don't mind about the result. – Mario Aug 13 '12 at 15:56
3

There are different approach to this.

You could use https://github.com/pgriess/node-webworker.

Or much better http://nodejs.org/docs/latest/api/cluster.html#cluster_cluster.

Those solutions are if you want to do a subprocess in Node, you could also simply spawn a new Node process and wait for the output (http://nodejs.org/api/all.html#all_child_process_spawn_command_args_options) but node-webworker is a wrapper around that solution and is a much cleaner.

3on
  • 6,291
  • 3
  • 26
  • 22
  • But I don't to wait at all. I want to call the subprocess and not more. I mean, if the main script dies or the http server ends I want the subprocess to continue. Thank you. – Mario Aug 10 '12 at 03:03
1

So after your last comment I know understand better what you want to do.

You want to spawn process not child process. The best and cleaner way to do this is to use some kind of demonizier to run them.

Have a look at forever:
https://github.com/nodejitsu/forever
https://github.com/nodejitsu/forever-monitor

This could be the perfect tool for you. I've never used it programatically, just cli. But this is what I'd look into.

3on
  • 6,291
  • 3
  • 26
  • 22