Sunny
Sunny

Reputation: 10075

Can I run a node child process with node script from a buffer and not from another file?

Currently I am generating a node script in a string/buffer from a parent node script. I am then writing the generate script in a file and executing that file in a child process. Finally I unlink the temp scriptfile.

Here is the simplified code:

fs.writeFileSync(scriptFile, program_code); 
script_output = child_process.execSync("node " + scriptFile).toString('utf8');
fs.unlinkSync(scriptFile);

Now that I have the output, I continue further processing. This works fine.

However, I feel that the overhead of writing to a temp file could be avoided if I can somehow run the node script from the in-memory buffer that I have rather than writing it to a file first.

I looked at the child_process module of node but did not find any way to do this. May be I missed something or is there some other way to do this? I am looking for something like this:

 script_output = child_process.execSync("node " + ...).toString('utf8')

Perhaps some shell programming trick? I looked at the -e and the -i option to node and that did not cut it. I tried the << here document shell feature with the -i option but the < prompt of the REPL mode appears to create a syntax issue.

Upvotes: 0

Views: 159

Answers (1)

keithmo
keithmo

Reputation: 4943

Look into Node's VM API. I haven't actually tried this, but it looks like vm.runInNewContext() might do what you need without launching a new copy of Node.

Upvotes: 1

Related Questions