简体   繁体   中英

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.

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.

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
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM