I am executing below code in NodeJS.
As seen below parent process spawns a child process and sets env variable. This variable is used to decide if process is parent or child when executing the file.
const {IS_CHILD} = process.env
if(IS_CHILD){
console.log('CHILD');
console.log('child pid = ',process.pid);
console.log('child env values = ',process.env);
}else{
const {parse} = require('path')
const {root} = parse(process.cwd());
console.log('PARENT');
console.log('parent pid = ',process.pid)
const {spawn} = require('child_process');
const sp = spawn(process.execPath,[__filename], {
cwd: root,
env: {IS_CHILD : true}
});
sp.stdout.pipe(process.stdout); // if this is commented
}
The issue I am facing is, if I comment out code sp.stdout.pipe(process.stdout)
inside parent process, the child process output is not shown on console. (Three lines inside IS_CHILD
if block )
If sp.stdout.pipe(process.stdout)
line is commented out, does that mean that process.env
for child process is also not written?
Can anybody please help here?
Am I missing anything here?
I was assuming that even if sp.stdout.pipe(process.stdout)
line is commented out, the child process
should have env variable
set in it as we have executed spawn command
If sp.stdout.pipe(process.stdout) line is commented out, does that mean that process.env for child process is also not written?
No. Environment variable is still there.
The output you get is expected.
When you run your script, it starts parent process. So what you will see in the console is output of parent process. Then, via spawn
you are spawning a child process. The child process is a completely different process. In order to see its output in the parent process, you can use piping as you do.
Another option is to use events of child process. You can attach a handler to child process' stdout data
event. eg
sp.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
For more info about child processes, see child process reference.
If you omit piping, the child process will write output to its own stdout which is different from parent process' stdout. Therefore, you don't see it.
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.