Send error to parent from child using Fork - node.js

I have the below code
// Parent.js
var cp = require('child_process');
var child = cp.fork('./pChild.js');
child.on('message', function(m) {
// Receive results from child process
console.log('received: ' + m);
});
// Send child process some work
child.send('First Fun');
// pChild.js
process.on('message', function(m) {
console.log("Helloooooooooo from pChild.js")
// Pass results back to parent process
process.send("Fun1 complete");
});
How to handle error in parent thrown from pChild.js and kill the process?

Unhandled errors in the child process will cause it to exit, which will emit the 'exit' event on the child object.
child.on('exit', function (code, signal) {
console.log('Child exited:', code, signal);
});
If the error is handled within the child, it can be sent as another message:
// in pChild.js
/* ... */.on('error', function (error) {
process.send({ error: error.message || error });
});
Updated answer
On child
process.on('uncaughtException', (err) => {
process.send({isError: true});
});
On master
master.on('message',({isError, data})=>{
if(isError) {
master.kill('SIGINT');
return;
}
console.log('message from child', data);
master.kill('SIGINT');
});

Related

process.on('signal') isn't working in node.js v18

I'm trying to catch "CTRL-C" on a command line node.js script.
process.on('signal', async (signal) => {
console.log('signal: ', signal);
if (signal === 'SIGINT') {
console.log('Received SIGINT. Calling save function...');
await amazon.saveData();
}
process.exit(0);
});
It doesn't get called.
Binding directly to the SIGINT event should work:
process.on('SIGINT', async (signal) => {
console.log('signal: ', signal);
console.log('Received SIGINT. Calling save function...');
await amazon.saveData();
process.exit(0);
});
You can find a list of supported events in the API reference: https://nodejs.org/api/process.html#signal-events
The following code should work
process.on('SIGINT', async (signal) => {
// ..
console.log('Received SIGINT. Calling save function...');
});

How to send command to child process nodejs

I am making an application that handles java commands and want to send java command to my child spawn process how can i achieve this
const {
spawn
} = require('child_process');
// Start child process
var child = spawn('java', ['-server', '-Xms1G', `-Xmx${document.getElementById('ram').value}G`, `-jar`, `${jarname}`], {
cwd: `${jarfolder}`
});
child.stdout.on('data', (data) => {
$("ol").append(`<li>${data}</li><br>`);
});
child.stderr.on('data', (data) => {
$("ol").append(`<li>${data}</li><br>`);
});
child.on('error', (error) => console.log(`error: ${error.message}`));
child.on('exit', (code, signal) => {
if (code) $("ol").append(`<li>Process exit with code: ${code}</li><br>`);
if (signal) $("ol").append(`<li>Process killed with signal: ${signal}</li><br>`);
});
demo code
example i have a button that calls a function and
function test(){
var command=document.getElementsById("command").innerHTML;
// send the command to terminatal

How to catch error while using fork child process in node?

I am using the fork method to spawn a child process in my electron app, my code looks like this
'use strict'
const fixPath = require('fix-path');
let func = () => {
fixPath();
const child = childProcess.fork('node /src/script.js --someFlags',
{
detached: true,
stdio: 'ignore',
}
});
child.on('error', (err) => {
console.log("\n\t\tERROR: spawn failed! (" + err + ")");
});
child.stderr.on('data', function(data) {
console.log('stdout: ' +data);
});
child.on('exit', (code, signal) => {
console.log(code);
console.log(signal);
});
child.unref();
But my child process exits immediately with exit code 1 and signal, Is there a way I can catch this error? When I use childprocess.exec method I can catch using stdout.on('error'... Is there a similar thing for fork method? If not any suggestions on how I can work around this?
Setting the option 'silent:true' and then using event handlers stderr.on() we can catch the error if any. Please check the sample code below:
let func = () => {
const child = childProcess.fork(path, args,
{
silent: true,
detached: true,
stdio: 'ignore',
}
});
child.on('error', (err) => {
console.log("\n\t\tERROR: spawn failed! (" + err + ")");
});
child.stderr.on('data', function(data) {
console.log('stdout: ' +data);
});
child.on('exit', (code, signal) => {
console.log(code);
console.log(signal);
});
child.unref();

How to capture response from child process in nodejs

I am trying to capture some response from my child process in master process. I can log information of child process in master process but unable to capture some return xyz response .
Here is code for master process:
var express = require('express');
var app = express();
const
fs = require('fs'),
cp = require('child_process');
app.get('/',onRequest );
function onRequest(request, response) {
var express = require('express');
var app = express();
var child= cp.spawn('node' ,['./child_process/block.js'],filestreamCallback);
child.stdout.on('data', function(data) {
console.log('stdout: ==== ' + data);
});
child.stderr.on('data', function(data) {
console.log('stdout: ' + data);
});
child.on('close', function(code) {
console.log('closing code: ' + code);
});
function filestreamCallback() {
response.writeHead(200, {'Content-Type': 'text/plain'});
baflog.info("Reading Stream completed");
response.write('Thanks for Your patience!\n');
response.end();
}
}
app.listen(5000);
console.log('Server started');
Child process : block.js
/*Keep waiting for 10 seconds*/
console.log("Waiting for child Process (block.js) to complete......");
var startTime = new Date().getTime();
while (new Date().getTime() < startTime + 10000);
ret_resp();
var response = {status:'success'};
function ret_resp(){
return response;
}
console.log("Thank You for waiting......");
Like in console i see output as :
stdout====: Waiting for child Process (block.js) to complete......
-punws-sohan
stdout: ==== Thank You for waiting......
I cannot see output for return response statement
Can anyone suggest how to capture response from child process?
First of all, the busy loop uses up unnecessary CPU time. Just use a setTimeout() instead. Example:
setTimeout(function() {
ret_resp();
// ...
}, 10000);
Secondly, you can't expect return to magically write the returned value to the parent process. Try this instead:
// parent.js
var child = cp.fork('./child_process/block.js', [], { silent: true });
child.stdout.on('data', function(data) {
console.log('stdout: ==== ' + data);
});
child.stderr.on('data', function(data) {
console.log('stdout: ' + data);
});
child.on('message', function(msg) {
console.log('message from child: ' + require('util').inspect(msg));
});
child.on('close', function(code) {
console.log('closing code: ' + code);
});
// child.js
console.log('Waiting for child Process (block.js) to complete......');
setTimeout(function() {
var response = {status:'success'};
function ret_resp() {
process.send(response);
}
ret_resp();
console.log('Thank You for waiting......');
}, 10000);

how to send message to parent process

Can I send message to parent process?
master
var child =child_process.fork();
child.send({msg:msg})
child process
process.on('message', function(){
});
// how to send message to parent??
In short use: process.send()
Longer example, I wrote awhile ago named forktest.js:
var cp = require('child_process');
if (!process.send) {
var p = cp.fork(__dirname + '/forktest');
p.send({
count: 10
});
p.on('message', function(data) {
process.exit(0);
});
} else {
process.on('message', function(data) {
console.log(data);
data.count--;
if (data.count === 0) {
process.send({});
process.exit(0);
}
var p = cp.fork(__dirname + '/forktest');
p.send(data);
p.on('message', function(data) {
process.send(data);
process.exit(0);
});
});
}

Resources