Hitesh
Hitesh

Reputation: 2055

Child/Secondary thread in node.js

I have a requirement, where I have to run a process independent of the main node thread. Basically, the purpose is to initiate the secondary process from the main node thread data, and not wait for the callback or any result, as the secondary process does not have to give anything back to the main thread.

I want to achieve this, without blocking the main nodejs thread, and the main thread should not care what happens after it passes the data to the secondary thread. Basically, the process of the main thread ends after sending the data to the secondary thread, as far as secondary process is concerned.

Any suggestions how I can achieve this? I read about the child process, webworkers, dnode and process nexttick, but I am not sure what is the best way to achieve it. I tried nexttick, but my experience has been that it still stays the part of the main thread, although asynchronously.

Upvotes: 1

Views: 852

Answers (2)

Hitesh
Hitesh

Reputation: 2055

I have implemented child process-fork for passing data for secondary / background processing to a child process (without disconnecting the child process). This seems to be doing my job well as of now. I will update if I face any issues or find a better solution.

//Main Process
var cp = require('child_process').fork('child.js');
cp.send(data);


//Child Process (child.js)
process.on('message', function(data){
 //do something with data
});

Upvotes: 0

SheetJS
SheetJS

Reputation: 22905

If your goal is just to start the process without regard for the output, you should use spawn with detached:true.

For passing data, you can write using stdin (see the example) or pass command line arguments or write to file and redirect.

Upvotes: 2

Related Questions