Search code examples
javascriptnode.jschild-process

nodejs child_process scope issue


I am using child_process(fork) of nodejs then I send data to a particular file and receive data but not console that data after receiving of process execution

first.js

var cp = require('child_process');
var child = cp.fork('./s/abc.js');
child.send({data:'this come from parent process'});
var x ;

child.on('message', function(m) {
console.log(m); // output:- this come from child process
x = m;
});
console.log(m);
console.log(x);

abc.js (./s/abc.js)

process.send({data:'this come from child process'});
var x ;

process.on('message', function(m) {
console.log(m); // output:- this come from parent process
});


Solution

  • use function to console value after scope end

    first.js

    var cp = require('child_process');
    var child = cp.fork('./s/abc.js');
    child.send({data:'this come from parent process'});
    var x ;

    child.on('message', function(m) {
    console.log(m); // output:- this come from child process
    callTempFun(m);
    });
    function callTempFun(m){
    console.log(m); // output:- this come from child process
    }

    abc.js (./s/abc.js)

    process.send({data:'this come from child process'});
    var x ;

    process.on('message', function(m) {
    console.log(m); // output:- this come from parent process
    });