Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data loss in Node.js child process

I'm trying to send data (as an object) to a child process in Node.js, however, all of my regular expressions get lost in transfer.

var arguments = {
    something: { 
       name: 'test',       
       age: 28,
       active; true          
    },
    otherThing: 'some string',
    regex: /test/i,
    regex2: new RegExp('test')
};

var child = cp.fork(path.join(__dirname, 'child.js'));

child.on('message', function (data) {
   console.log(data);
});

child.send(arguments);

In the child.js file I have this at the top:

process.on('message', function () {
   console.log(arguments); // This is where the data has changed
});

When the log is output from the child process the arguments object instead looks like this:

{
    something: {
        name: 'test',
        age: 28,
        active: true
    },
    otherThing: 'some string',
    regex: {},
    regex2: {}
}

So far unable to find anything elsewhere about why this may be happening, any ideas?

like image 315
Jon Watkins Avatar asked May 08 '26 08:05

Jon Watkins


1 Answers

Because they are completely separate JavaScript processes, you can't send objects. When you pass an object, it gets serialized to JSON and parsed by the child. (See the docs.)

JSON does not support serializing regex objects. (Try putting JSON.stringify(/abc/) through your console -- you get back "{}".)

To include regexes in a JSON object, you can use the json-fn module. It supports serializing functions, dates, and regexes. (It was actually thanks to an issue i raised that they added regex support. :))

You could then do something like:

var JSONfn = require('json-fn');
var arguments = {
    something: { 
       name: 'test',       
       age: 28,
       active; true          
    },
    otherThing: 'some string',
    regex: /test/i,
    regex2: new RegExp('test')
};

var child = cp.fork(path.join(__dirname, 'child.js'));
});

child.send(JSONfn.stringify(arguments));

and:

var JSONfn = require('json-fn');
process.on('message', function (data) {
   console.log(JSONfn.parse(data))); // This is where the data has changed
});
like image 149
Scimonster Avatar answered May 09 '26 21:05

Scimonster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!