That is the problem I need to get all the outputs of a script that I run from node js and get all of them, now I get them but only when the script process is completely finished and I want to get them every time it sends them. This is the code:
exec(line, (error, stdout, stderr) => {
if (error) {
out = "!!!!!!! ERROR EN ComandLine (" + Today() + ")-------!! : \n " + error.message;
console.log(_out);
WriteLog(_out);
socket.send("ERROR");
return;
}
//Standar error
if (stderr) {
out = "!!!!!!! STDERROR EN ComandLine (" + Today() + ") : \n " + stderr.message
console.log(_out);
WriteLog(_out);
socket.send("ERROR");
return;
}
//resultado final
if (stdout.toString().includes("Se fini")) {
console.log("Server end task");
_generating = false;
}
_out = "------- STD OUT ------- (" + Today() + ") : \n " + stdout.message;
console.log(_out);
WriteLog(_out);
});
}
I suppose that you are using child_process.exec. For your use case child_process.spawn would be the right choice I think since it is emitting events you can listen to.
See the nodejs doc https://nodejs.org/api/child_process.html#child_processspawncommand-args-options
Something like this should roughly implement the behavior you are looking for.
const { spawn } = require('child_process');
const cmd = spawn(line);
cmd.stdout.on('data', (data) => {
_out = "------- STD OUT ------- (" + Today() + ") : \n " + data;
console.log(_out);
WriteLog(_out);
});
cmd.stderr.on('data', (data) => {
_out = "!!!!!!! STDERROR EN ComandLine (" + Today() + ") : \n " + data
console.log(_out);
WriteLog(_out);
socket.send("ERROR");
return;
});
cmd.on('close', (code) => {
console.log("Server end task");
_generating = false;
});