Skip to content

Instantly share code, notes, and snippets.

@lap00zza
Created November 13, 2018 19:06
Show Gist options
  • Select an option

  • Save lap00zza/7da2b7738cd89d08afabd53be81a6fc4 to your computer and use it in GitHub Desktop.

Select an option

Save lap00zza/7da2b7738cd89d08afabd53be81a6fc4 to your computer and use it in GitHub Desktop.

Revisions

  1. lap00zza created this gist Nov 13, 2018.
    55 changes: 55 additions & 0 deletions evalNode.js
    Original 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 ] }