Node.js REPL

交互式控制台:读、求值、打印、循环,以及它藏着的调试入口。

Beginner
Key Points`node` 不带参数就进 REPL;`.` 开头的命令是元命令,`_` 保存上一个结果。

进与退

Bash
node
Output
$ node
Welcome to Node.js v22.22.2.
Type ".help" for more information.
> 1 + 2
3
> [1, 2, 3].map(x => x * 2)
[ 2, 4, 6 ]
> .exit

元命令

CommandEffect
.help列出所有元命令
.exit退出(或按两次 Ctrl+C)
.clear清屏并重置上下文
.save ./s.js把本次会话存成文件
.load ./s.js载入文件里的语句
.editor进入多行编辑,Ctrl+D 结束

几个好用的细节

JavaScript
> const a = [1, 2, 3]
undefined
> a.length
3
> _
3
> _ * 10
30
> require('node:os').cpus().length
8
> .exit

_ holds the previous value; undefined is printed because a const declaration returns nothing. In the REPL you can require built-ins and installed packages, which makes it great for testing one API call.

不用进 REPL 的写法

Bash
node -e "console.log(process.version)"
node -p "2 ** 10"
node --input-type=module -e "import os from 'node:os'; console.log(os.platform())"
Output
v22.22.2
1024
win32
node -p prints the expression result; node -e only executes. -p is handier when a shell script just needs one value.

Friends & Partners