Created
November 13, 2018 19:06
-
-
Save lap00zza/7da2b7738cd89d08afabd53be81a6fc4 to your computer and use it in GitHub Desktop.
Revisions
-
lap00zza created this gist
Nov 13, 2018 .There are no files selected for viewing
This file contains hidden or 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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,55 @@ 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 ] }