Node.js の REPL に関する tips

REPL で複数行の入力を行う方法

Node.js の REPL で複数行の入力を行うには .editor とタイプすればよい。.editor とタイプしてから Ctrl-d をタイプするまでの範囲をインタプリタが解釈する。

$ node
Welcome to Node.js v12.18.0.
Type ".help" for more information.
> .editor
// Entering editor mode (^D to finish, ^C to cancel)
const foo = 'bar'
foo

(^d をタイプして REPL を終了する)

'bar'

REPL で直前に評価した値を再利用する

Node.js の REPL で直前の値を参照したい場合は _ 変数を使う。次に使用例を示す。

$ node
Welcome to Node.js v14.2.0.
Type ".help" for more information.
> [1, 2, 3]
[ 1, 2, 3 ]
> _[0]
1

なお、直前のエラーは _error 変数に入れられる。