【问题标题】:How can I make the Node REPL print the result only?如何让 Node REPL 只打印结果?
【发布时间】:2017-11-30 23:41:08
【问题描述】:

我想使用.load myFile.js 运行脚本,但我不想打印文件中的所有内容,只打印文件的值/结果。我在我的项目中使用 Electron、xterm.js 和 node-pty。

例如,使用以下代码:

// type your code here

function sum(x, y) {
  return x + y
}

sum(2, 3)

我得到这样的东西:

> // type your code here
undefined
> function sum(x, y) {
...   return x + y
... }
undefined
> sum(2, 3)
5
>

【问题讨论】:

  • 在 REPL 外部运行程序?那是 REPL 的“P[rint]”部分。 (话虽这么说,各种 REPL 都有许多配置选项,所以..)
  • @user2864740 是的,我知道,问题是我已经想进入 repl。我正在尝试完成类似于 repl.it 的事情。

标签: javascript node.js read-eval-print-loop pty xtermjs


【解决方案1】:

如果您对在当前范围内运行的代码感到满意,请eval it:

> eval(fs.readFileSync('myFile.js', 'utf8'))
5

如果你想要一个新的范围,vm.runInNewContext(这不是安全问题,只是范围清洁):

> vm.runInNewContext(fs.readFileSync('myFile.js', 'utf8'))
5

require can be passed in its second argument 这样的全局变量。

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 1970-01-01
    相关资源
    最近更新 更多