如何使用 Node.js REPL
¥How to use the Node.js REPL
node
命令是我们用来运行 Node.js 脚本的命令:
¥The node
command is the one we use to run our Node.js scripts:
node script.js
如果我们运行 node
命令而不执行任何脚本或不带任何参数,我们将启动 REPL 会话:
¥If we run the node
command without any script to execute or without any arguments, we start a REPL session:
node
注意:
REPL
代表读取评估打印循环,它是一种编程语言环境(基本上是一个控制台窗口),将单个表达式作为用户输入并在执行后将结果返回控制台。REPL 会话提供了一种快速测试简单 JavaScript 代码的便捷方法。¥Note:
REPL
stands for Read Evaluate Print Loop, and it is a programming language environment (basically a console window) that takes single expression as user input and returns the result back to the console after execution. The REPL session provides a convenient way to quickly test simple JavaScript code.
如果你现在在终端中尝试,将发生以下情况:
¥If you try it now in your terminal, this is what happens:
❯ node
>
该命令保持空闲模式并等待我们输入某些内容。
¥The command stays in idle mode and waits for us to enter something.
提示:如果你不确定如何打开终端,请谷歌搜索 "如何在操作系统上打开终端"。
¥Tip: if you are unsure how to open your terminal, google "How to open terminal on your-operating-system".
更准确地说,REPL 正在等待我们输入一些 JavaScript 代码。
¥The REPL is waiting for us to enter some JavaScript code, to be more precise.
从简单开始并输入
¥Start simple and enter
> console.log('test')
test
undefined
>
第一个值 test
是我们告诉控制台打印的输出,然后我们得到 undefined
,它是运行 console.log()
的返回值。Node 读取此行代码,对其进行评估,打印结果,然后返回等待更多代码行。Node 将对我们在 REPL 中执行的每段代码循环执行这三个步骤,直到我们退出会话。这就是 REPL 名称的由来。
¥The first value, test
, is the output we told the console to print, then we get undefined
which is the return value of running console.log()
.
Node read this line of code, evaluated it, printed the result, and then went back to waiting for more lines of code. Node will loop through these three steps for every piece of code we execute in the REPL until we exit the session. That is where the REPL got its name.
Node 会自动打印任何一行 JavaScript 代码的结果,而无需指示它这样做。例如,输入以下行并按回车键:
¥Node automatically prints the result of any line of JavaScript code without the need to instruct it to do so. For example, type in the following line and press enter:
> 5 === '5'
false
>
注意上面两行输出的区别。Node REPL 在执行 console.log()
后打印 undefined
,而另一方面,它只打印 5 === '5'
的结果。你需要记住,前者只是 JavaScript 中的一个语句,而后者是一个表达式。
¥Note the difference in the outputs of the above two lines. The Node REPL printed undefined
after executing console.log()
, while on the other hand, it just printed the result of 5 === '5'
. You need to keep in mind that the former is just a statement in JavaScript, and the latter is an expression.
在某些情况下,你要测试的代码可能需要多行。例如,假设你想定义一个生成随机数的函数,在 REPL 会话中输入以下行并按回车键:
¥In some cases, the code you want to test might need multiple lines. For example, say you want to define a function that generates a random number, in the REPL session type in the following line and press enter:
function generateRandom() {
...
Node REPL 足够智能,可以确定你尚未完成代码编写,并且它将进入多行模式供你输入更多代码。现在完成你的函数定义并按回车键:
¥The Node REPL is smart enough to determine that you are not done writing your code yet, and it will go into a multi-line mode for you to type in more code. Now finish your function definition and press enter:
function generateRandom() {
...return Math.random()
}
undefined
_
特殊变量
¥The _
special variable
如果在某些代码之后输入 _
,它将打印最后一个操作的结果。
¥If after some code you type _
, that is going to print the result of the last operation.
向上箭头键
¥The Up arrow key
如果按下 up
箭头键,你将可以访问当前甚至之前的 REPL 会话中执行的先前代码行的历史记录。
¥If you press the up
arrow key, you will get access to the history of the previous lines of code executed in the current, and even previous REPL sessions.
点命令
¥Dot commands
REPL 有一些特殊命令,所有命令都以点 .
开头。它们是
¥The REPL has some special commands, all starting with a dot .
. They are
-
.help
:显示点命令帮助¥
.help
: shows the dot commands help -
.editor
:启用编辑器模式,轻松编写多行 JavaScript 代码。一旦你处于此模式,请输入 ctrl-D 以运行你编写的代码。¥
.editor
: enables editor mode, to write multiline JavaScript code with ease. Once you are in this mode, enter ctrl-D to run the code you wrote. -
.break
:输入多行表达式时,输入 .break 命令将中止进一步输入。与按 ctrl-C 相同。¥
.break
: when inputting a multi-line expression, entering the .break command will abort further input. Same as pressing ctrl-C. -
.clear
:将 REPL 上下文重置为空对象并清除当前正在输入的任何多行表达式。¥
.clear
: resets the REPL context to an empty object and clears any multi-line expression currently being input. -
.load
:加载 JavaScript 文件,相对于当前工作目录¥
.load
: loads a JavaScript file, relative to the current working directory -
.save
:将你在 REPL 会话中输入的所有内容保存到文件(指定文件名)¥
.save
: saves all you entered in the REPL session to a file (specify the filename) -
.exit
:退出 repl(与按 ctrl-C 两次相同)¥
.exit
: exits the repl (same as pressing ctrl-C two times)
REPL 知道你何时输入多行语句,而无需调用 .editor
。
¥The REPL knows when you are typing a multi-line statement without the need to invoke .editor
.
例如,如果你开始输入如下迭代:
¥For example if you start typing an iteration like this:
[1, 2, 3].forEach(num => {
当你按下 enter
时,REPL 将转到以 3 个点开头的新行,表示你现在可以继续处理该块。
¥and you press enter
, the REPL will go to a new line that starts with 3 dots, indicating you can now continue to work on that block.
... console.log(num)
... })
如果你在行末输入 .break
,多行模式将停止并且不会执行该语句。
¥If you type .break
at the end of a line, the multiline mode will stop and the statement will not be executed.
从 JavaScript 文件运行 REPL
¥Run REPL from JavaScript file
我们可以使用 repl
在 JavaScript 文件中导入 REPL。
¥We can import the REPL in a JavaScript file using repl
.
const repl = require('node:repl');
使用 repl 变量,我们可以执行各种操作。要启动 REPL 命令提示符,请输入以下行
¥Using the repl variable we can perform various operations. To start the REPL command prompt, type in the following line
repl.start();
在命令行中运行文件。
¥Run the file in the command line.
node repl.js
你可以传递一个显示 REPL 启动时间的字符串。默认值为 '>'(带有尾随空格),但我们可以定义自定义提示。
¥You can pass a string which shows when the REPL starts. The default is '> ' (with a trailing space), but we can define custom prompt.
// a Unix style prompt
const local = repl.start('$ ');
你可以在退出 REPL 时显示一条消息
¥You can display a message while exiting the REPL
local.on('exit', () => {
console.log('exiting repl');
process.exit();
});
你可以在 repl 文档 中阅读有关 REPL 模块的更多信息。
¥You can read more about the REPL module in the repl documentation.