Skip to content

Instantly share code, notes, and snippets.

@lap00zza lap00zza/evalNode.js
Created Nov 13, 2018

Embed
What would you like to do?
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
You can’t perform that action at this time.