nodejs中REPL的使用

Use of REPL in node js

  1. REPL在nodejs中有什么用?
  2. 使用 REPL 有哪些use-cases/scenario?
  3. 什么时候应该在nodejs中使用REPL节点模块?

我已经理解 API 文档,如何包含 REPL 模块以及如何使用提示和 eval 启动 REPL 实例。

但是谁能帮我理解上面的问题?这样我就可以了解如何使用 REPL 模块?

What are the use-cases/scenario for using REPL?

我经常看到它(或者 Chrome 的控制台,它是 JavaScript REPL as well) used in tech talks as a quick way to demonstrate what different expressions evaluate to. Let's image you're holding a talk about Equality in JavaScript and want to show that NaN strangely is not equal to itself

您可以通过以下方式证明这一点:

  • 运行ning node 终端中没有参数(这会启动 REPL)
  • 输入 NaN == NaN 并按 Enter(REPL 将计算表达式)
  • 假装惊讶输出是false

When should I use the REPL node module in nodejs?

当您想将 Node.js REPL 作为应用程序的一部分实施时,例如通过在 Web 浏览器中通过 "remote terminal" 公开它(出于安全原因不推荐这样做)。

例子

复制通过调用 node

显示的 REPL
const repl = require('repl')
const server = repl.start()

使用 REPLServer 的流 API

fs-repl.js 文件:

const repl = require('repl')
const fs = require('fs')
const { Readable } = require('stream')

const input = new fs.createReadStream('./input.js')

const server = repl.start({
  input,
  output: process.stdout
})

input.js 文件:

40 + 2
NaN
["hello", "world"].join(" ")

您现在可以 运行 node fs-repl 并且您将得到以下输出:

> 40 + 2
42
> NaN
NaN
> ["hello", "world"].join(" ")
'hello world'

此输出显然可以传递到 Writable stream other than process.stdout by changing the output 选项中。