简体   繁体   中英

Node.js REPL syntax with empty parens

Consider the following exciting javascript code:

(function(){console.log("wtf?");})()
function(){console.log("wtf?");}()

put this code in a file dumb.js and run with node, and you get the following result:

private/tmp/junk/dumb.js:2
function(){console.log("wtf?");}()
        ^
SyntaxError: Unexpected token (
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:528:28)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.runMain (module.js:590:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

Not unexpectedly, that's a syntax error. However, on the Node REPL, we see

$ node
> (function(){console.log("wtf?");})()
wtf?
undefined
> function(){console.log("wtf?");}()
...

At that point, nothing but .break , ^C , or the like breaks out of the continuation lines.

I don't understand.

Could someone explain what the REPL is looking for, or otherwise explain this behavior?

Per node.js documentation :

As a user is typing input into the REPL prompt, pressing the key will send the current line of input to the eval function. In order to support multi-line input, the eval function can return an instance of repl.Recoverable to the provided callback function:

When you execute an entire file via node "filename", node has the ability to check for syntax errors. This is because the file content will not change.

When you have a syntax error after a "{" in the node repl, it assumes you are entering a multi-line statement. The majority of multi-line statements aren't correct syntax until they are closed. Therefore, it will not throw a syntax error until the statement is closed. Also, you won't be able to close out the multi-line statement because node isn't able to correctly parse your code after the syntax error.

What you are seeing with your incorrect syntax is exactly what is described in the above documentation.

The problem is that you are defining second function without name. First one is OK because it's IIFE function but the second one is normal function, and you need to assign name on it. That's why terminal showing you ... because it's waiting for you to finish function. Because of your mistake Node REPL assumes that it's a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM