Node.js readline:意外的令牌 =>

Node.js readline: Unexpected token =>

我正在学习 node.js 并且需要将 readline 用于项目。我有以下直接来自 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();
});

但是当我 运行 代码通过 node try.js 命令,它不断给出如下错误:

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

=> 语法,称为箭头函数,是 JavaScript 的一项相对较新的功能。您需要一个类似的新版本的 Node 才能利用它。

升级您的节点版本。

箭头函数现在可以在节点(版本 4.0.0)中使用,请参阅此处:ECMAScript 2015 (ES6) in Node.js

查看你是哪个版本运行node -v

您可能需要升级,请在此处查看兼容性 table 以了解还有哪些可用的:

Node Compatibility Table

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.

您可以升级 node.js 版本或使用旧语法,如下所示:

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

(请注意,这些语法之间还有一个区别:this 变量的行为不同。这对本示例无关紧要,但在其他示例中可能很重要。)

对于已经升级节点并且 运行 陷入同样错误的人:对我来说,这个错误来自 eslint。我在 package.json:

中使用 node 14
  "engines": {
    "node": "14"
  },

但是在将 linter .eslintrc.js 配置更新为以下内容后才消除了错误:

  "parserOptions": {
    "ecmaVersion": 8,
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true,
    },
    "sourceType": "module",
  },