Node.js REPL
交互式控制台:读、求值、打印、循环,以及它藏着的调试入口。
Key Points`node` 不带参数就进 REPL;`.` 开头的命令是元命令,`_` 保存上一个结果。
进与退
Bash
nodeOutput
$ 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元命令
| Command | Effect |
|---|---|
.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
win32node -p prints the expression result; node -e only executes. -p is handier when a shell script just needs one value.进与退
Bash
nodeOutput
$ 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元命令
| 命令 | 作用 |
|---|---|
.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_ 是上一个表达式的值;undefined 也会被打印,因为 const 声明本身没有返回值。REPL 里可以直接 require 内置模块和已安装的包,很适合验证一行 API。
不用进 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
win32node -p 会自动打印表达式结果,node -e 只执行不打印。写 shell 脚本时用 -p 取一个值更省事。