如何启动一个可以访问node.js中的局部变量的repl?

问题描述 投票:0回答:1

就像 from IPython import embed; embed() 但对于 node.

我想用编程方式打开一个REPL shell,至少能够读取本地变量。能够改变它们也是一个优点。

javascript node.js read-eval-print-loop deno
1个回答
2
投票

对于 deno 标题说的是Node.js,标签deno)你可以用 Deno.run 执行 deno 并写信给 stdin 并从 stdout.

下面就可以了。

const p = Deno.run({
    cmd: ["deno"],
    stdin: "piped",
    stdout: "piped",
    stderr: "piped"
  });

async function read(waitForMessage) {
    const reader = Deno.iter(p.stdout)
    let res = '';
    for await(const chunk of reader) {      
        res += new TextDecoder().decode(chunk);
        console.log('Chunk', res, '---')
        // improve this, you should wait until the last chunk 
        // is read in case of a command resulting in a big output
        if(!waitForMessage)
            return res;
        else if(res.includes(waitForMessage))
            return res;
    }
}

async function writeCommand(command) {
    const msg = new TextEncoder().encode(command + '\n'); 

    console.log('Command: ', command)
    const readPromise = read();
    // write command
    await p.stdin.write(msg);
    // Wait for output
    const value = await readPromise

    return value;
}

// Wait for initial output: 
// Deno 1.0.0
// exit using ctrl+d or close()
await read('ctrl+d or close()');


await writeCommand('let x = 5;')
let value = await writeCommand('x') // read x
console.log('Value: ', value)

await writeCommand('x = 6;')
value = await writeCommand('x') // read x
console.log('Value: ', value)

如果你运行这个代码,输出的结果是:

Command: let x = 5;
Command: x
Value: 5

Command:  x = 6;
Command:  x
Value:  6

还有一些需要改进的地方,比如处理... stderr 但你明白我的意思

© www.soinside.com 2019 - 2024. All rights reserved.