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

Hap*_*ace 8 javascript node.js read-eval-print-loop deno

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

我想以编程方式打开一个 REPL shell,并且至少能够读取局部变量。能够改变它们也是一个加分项。

mfu*_*n26 2

您可以构建类似于内置 Deno REPL 的 REPL,并使用危险 eval函数评估表达式。通过它您将能够访问局部变量和其他东西(例如window)。

repl.ts

import { readLines, writeAll } from "https://deno.land/std@0.106.0/io/mod.ts";

export default async function repl(evaluate: (x: string) => unknown) {
  await writeOutput("exit using ctrl+d or close()\n");
  await writeOutput("> ");
  for await (const input of readInputs()) {
    try {
      const value = evaluate(input);
      const output = `${Deno.inspect(value, { colors: !Deno.noColor })}\n`;
      await writeOutput(output);
      await writeOutput("> ");
    } catch (error) {
      await writeError(error);
    }
  }
}

async function* readInputs(): AsyncIterableIterator<string> {
  yield* readLines(Deno.stdin);
}

async function writeOutput(output: string) {
  await writeAll(Deno.stdout, new TextEncoder().encode(output));
}

async function writeError(error: unknown) {
  await writeAll(Deno.stderr, new TextEncoder().encode(`Uncaught ${error}\n`));
}
Run Code Online (Sandbox Code Playgroud)

repl_demo.ts

import repl from "./repl.ts";

let a = 1;
let b = 2;
let c = 3;

await repl((x) => eval(x));
Run Code Online (Sandbox Code Playgroud)

用法示例

% deno run repl_demo.ts
exit using ctrl+d or close()
> a
1
> a = 40
40
> a + b
42
Run Code Online (Sandbox Code Playgroud)