Sam Sam -4 years ago 54
Node.js Question

How to fork a process in Node.js to run JS code from a buffer available in parent rather than from a file?

I am using


to fork a child process and to execute the JS in scriptFile. The problem is that I want to optimize it because the JS code I want to run is already available in a buffer in the parent. I am now writing it to a file and then specifying that path to child_process.fork. This involves two redundant I/O. First I write the JS to a file in the parent. It is then read by the child process.

Any way to prevent this?

Answer Source

Putting my comment into answer as requested...

I don't think what you ask for exists.

You could start a generic node.js app that was already on disk where that app is coded to get its code from stdinput and then you could feed your code to stdinput for the stub app to read. No extra reads or writes of your code that way.

Here's an example of two simple apps that do this:

First, the app that just reads from stdin and executes it as Javascript:

// read-from-stdin.js
let input = "";
process.stdin.on('data', function(chunk) {
    input += chunk;
process.stdin.on('end', function() {
process.stdin.on('error', function(err) {
    console.log("err:", err);

Then, an app that launches that app and passes it some JS to execute:

const spawn = require('child_process').spawn;

let child = spawn('node', ['read-from-stdin.js'], {stdio: ['pipe', 'inherit', 'inherit']});
child.on('error', function(err) {
    console.log("err on spawn ", err);
child.stdin.write("console.log('Hello from your parent')");

When I run the second code, it launches the first code and sends it a console.log() statement via stdin which the code in the first app reads from stdin and then executes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download