repl

Node.js REPL (交互式解释器)

Node.js REPL (Read Eval Print Loop:交互式解释器)表示一个一个电脑的环境。类似Windows系统的终端或Unix/Linux shell,可以在终端中输入命令,并接收系统的响应。

  • 读取 - 读取用户输入,解析输入了Javascript 数据结构并存储在内存中。
  • 执行 - 执行输入的数据结构。
  • 打印 - 输出结果。
  • 循环 - 循环操作以上步骤直到用户两次按下ctrl-c 退出。

Node的交互式解释器可以很好的调试Javascript代码。

启动Node终端

> node

简单表达式运算

> 1 + 4
5
> 5 / 2
2.5
> 3 * 6
18
> 1 + ( 2 * 3 ) -4
3
>

使用变量

可以将变量声明在内存中,并在需要的时候使用它。

变量声明需要使用var 关键字,否则会被直接打印出来。

使用var 关键字声明的变量可以使用console.log()来输出变量。

> node
> x = 10
10
> var y = 20
undefined
> x + y
30
> console.log('Hello World')
Hello World
undefined

多行表达式

Node REPL 支持输入多行表达式,这就有点类似Javascript。

$ node
> var x = 0
undefined
> do {
... x++;
... console.log("x: " + x);
... } while ( x < 5 );
x: 1
x: 2
x: 3
x: 4
x: 5
undefined
>

…三个点的符号是系统自动生成的,回车换行即可。Node 会自动检测是否为连续的表达式。

下划线变量

可以使用下划线(_)获取上一个表达式的运算结果:

> 1 + 2
3
> console.log(_)
3
undefined
>

REPl 命令

  • ctrl+c 退出当前终端

  • ctrl+c 连续按下两次,退出Node REPL

  • ctrl+d 退出Node REPL

  • 向上/向下 查看历史输入命令

  • tab键 列出当前命令

  • .help 列出使用命令

  • .break 退出多行表达式

  • .clear 退出多行表达式

  • .exit 退出Node REPL

  • .save filename 保存当前的 Node REPL 会话到指定文件

  • .load filename 载入当前Node RPEL 会话的文件内容

    .help
    .break Sometimes you get stuck, this gets you out
    .clear Alias for .break
    .editor Enter editor mode
    .exit Exit the repl
    .help Print this help message
    .load Load JS from a file into the REPL session
    .save Save all evaluated commands in this REPL session to a file