Node.js readline: Unexpected token =>

2019-02-17 20:01发布

问题:

I am learning node.js and need to use readline for a project. I have the following code directly from the readline module example.

const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What do you think of Node.js? ', (answer) => {
  // TODO: Log the answer in a database
  console.log('Thank you for your valuable feedback:', answer);

  rl.close();
});

But when I run the code via node try.js command, it keeps giving out the errors like below:

rl.question('What is your favorite food?', (answer) => {
                                                    ^^
SyntaxError: Unexpected token =>
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

回答1:

Arrow functions, one of the new features of the ECMAScript 6 standard, were introduced to node.js (as stable feature) only in version 4.0.0.

You can either upgrade your node.js version or use the old syntax, which would look like this:

rl.question('What do you think of Node.js? ', function(answer) {
  // TODO: Log the answer in a database
  console.log('Thank you for your valuable feedback:', answer);

  rl.close();
});

(Note that there is one more difference between those syntaxes: The this variable behaves differently. It doesn't matter for this example, but it may in others.)



回答2:

Upgrade your node version.

Arrow functions now work in node (version 4.0.0) see here: ECMAScript 2015 (ES6) in Node.js

Check to see which version you are running with node -v

You likely need to upgrade check out the compatibility table here to see what else is available:

Node Compatibility Table



回答3:

The => syntax, known as an Arrow Function, is a relatively new feature of JavaScript. You'll need a similarly new version of Node to take advantage of it.