Created
November 13, 2018 19:06
-
-
Save lap00zza/7da2b7738cd89d08afabd53be81a6fc4 to your computer and use it in GitHub Desktop.
Evaluate JS code in a node child process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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