Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write multiple lines of code in Node REPL

I would like to evaluate

var foo = "foo";
console.log(foo);

as a block, instead of evaluating line by line

var foo = "foo";
undefined
console.log(foo);
foo
undefined

Is there a simple way to move the prompt to the next line?

like image 984
aksanoble Avatar asked Mar 23 '15 05:03

aksanoble


People also ask

How do you type multiple lines in Replit?

Instead of typing out all three lines, you can type out the first one, leave your cursor position on that line, and press Shift+Alt+down twice. This will create two copies of the line, directly below the original one, and then you can simply change the number in the variable to account for the second two balls.

How do you go to the next line in REPL?

Ever wanted to insert a new blank line into something you're working on at the REPL? Just pressing <Enter> is going to execute the command! Note: this trick works mid-line to break a long line, too!


3 Answers

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 commands https://nodejs.org/api/repl.html#repl_commands_and_special_keys

like image 199
jhnstn Avatar answered Oct 18 '22 07:10

jhnstn


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);
... }
foo
undefined

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.

like image 41
Phssthpok Avatar answered Oct 18 '22 07:10

Phssthpok


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 ;)

like image 3
benjaminz Avatar answered Oct 18 '22 05:10

benjaminz