Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a function in a new process node

I am looking for a way (a npm module or a lib would be really useful) to run a javascript function in a new process. However, I don't want to define this function in a different file. I am looking for something like the POSIX fork mechanism.

how can I achieve this in node?

like image 696
Giuseppe Pes Avatar asked Mar 16 '23 02:03

Giuseppe Pes


1 Answers

You can fork new processes using child_process.fork. It accepts a separate module, but if you must have it all contained in one file you could give your script a mode parameter:

var child_process = require('child_process');
var mode = process.argv[2] ? process.argv[2] : 'default';

var modes = {
    default: function() {
        console.log('I am the default, I will fork a child');
        child_process.fork(__filename, ['child']);
    },
    child: function() {
        console.log('I am the child!');
    }
};

modes[mode]();
like image 189
Andrew Lavers Avatar answered Mar 18 '23 15:03

Andrew Lavers