Skip to content

Instantly share code, notes, and snippets.

@lap00zza
Created November 13, 2018 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lap00zza/7da2b7738cd89d08afabd53be81a6fc4 to your computer and use it in GitHub Desktop.
Save lap00zza/7da2b7738cd89d08afabd53be81a6fc4 to your computer and use it in GitHub Desktop.
Evaluate JS code in a node child process
const { spawn } = require("child_process");
const { Readable, Duplex, Writable } = require("stream");
const wrapRS = txt => {
const r = new Readable();
r._read = () => {
r.push(txt);
r.push(null);
};
return r;
};
const promiseWriter = fn => {
const w = new Writable();
w._write = (chunk, _, next) => {
fn(chunk.toString());
// write only once
w.destroy();
};
return w;
};
const Node = () => {
const d = new Duplex();
const proc = spawn("node");
proc.stdout.on("data", chunk => d.push(chunk));
proc.stdout.on("end", () => d.push(null));
d._write = (chunk, _, next) => {
proc.stdin.write(chunk);
next();
};
d._read = () => undefined;
d.on("finish", () => proc.stdin.end());
return d;
};
const evalCode = code => {
return new Promise(resolve => {
wrapRS(code)
.pipe(Node())
.pipe(promiseWriter(resolve));
});
};
// TESTING TIME
const testObject = {
a: 1,
b: { c: 1, d: 1 },
d: [1, 2, 3, 4, 5]
};
evalCode("console.log(1212)").then(x => console.log(x));
// 1212
evalCode(`console.log(${JSON.stringify(testObject)})`).then(x => console.log(x));
// { a: 1, b: { c: 1, d: 1 }, d: [ 1, 2, 3, 4, 5 ] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment