How to write multiple lines of code in Node REPL How to write multiple lines of code in Node REPL node.js node.js

How to write multiple lines of code in Node REPL


Node v6.4 has an editor mode. At the repl prompt type .editor and you can input multiple lines.

example

$ 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.

Here are the docs on all the special repl commandshttps://nodejs.org/api/repl.html#repl_commands_and_special_keys


You can use if(1){ to start a block that will not finish until you enter }. It will print the value of the last line of the block.

> {... var foo = "foo";... console.log(foo);... }fooundefined

In multiline mode you miss out on a lot of REPL niceties such as autocompletion and immediate notification of syntax errors. If you get stuck in multiline mode due to some syntax error within the block, use ^C to return to the normal prompt.


jhnstn's solution is perfect, but in case you are looking for other alternatives, you can put the code inside a multiline string and then eval it like so:

> let myLongCode = `... let a = 1;... let b = 2;... console.log(a + b);... `;> eval(myLongCode)> 3

Of course this is a hack ;)