如何在Node REPL中编写多行代码

use*_*377 42 command-prompt node.js read-eval-print-loop node-repl

我想评价一下

var foo = "foo";
console.log(foo);
Run Code Online (Sandbox Code Playgroud)

作为一个块,而不是逐行评估

var foo = "foo";
undefined
console.log(foo);
foo
undefined
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法将提示移动到下一行?

小智 72

节点v6.4有一个editor模式.在repl提示符下键入.editor,您可以输入多行.

$ node                                                                                                   
> .editor
// Entering editor mode (^D to finish, ^C to cancel)
const fn = there => `why hello ${there}`;
fn('multiline');
// hit ^D 
'why hello multiline'
> // 'block' gets evaluated and back in single line mode.
Run Code Online (Sandbox Code Playgroud)

以下是所有特殊repl命令的文档 https://nodejs.org/api/repl.html#repl_commands_and_special_keys


Phs*_*pok 19

您可以if(1){用来启动一个在您输入之前无法完成的块}.它将打印块的最后一行的值.

> {
... var foo = "foo";
... console.log(foo);
... }
foo
undefined
Run Code Online (Sandbox Code Playgroud)

在多线模式下,您会错过许多REPL细节,例如自动完成和语法错误的即时通知.如果由于块内的某些语法错误而陷入多线模式,请使用^C返回正常提示.