11

我正在学习 node.js,需要readline用于一个项目。我直接从readline 模块示例中获得了以下代码。

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
4

4 回答 4

20

箭头函数是ECMAScript 6 标准的新特性之一,仅在4.0.0 版本中被引入 node.js(作为稳定特性)。

您可以升级 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变量的行为不同。对于这个例子无关紧要,但在其他例子中可能。)

于 2016-04-25T14:39:48.463 回答
3

升级您的节点版本。

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

检查您正在运行的版本node -v

您可能需要升级查看兼容性表,看看还有什么可用的:

节点兼容性表

于 2016-04-25T14:38:53.390 回答
1

对于已经升级节点并遇到相同错误的人:对我来说,这个错误来自 eslint。我在我的中使用节点 14package.json

  "engines": {
    "node": "14"
  },

但只有在将 linter 配置更新为以下内容后才摆脱了错误.eslintrc.js

  "parserOptions": {
    "ecmaVersion": 8,
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true,
    },
    "sourceType": "module",
  },
于 2021-12-20T11:45:29.107 回答
0

这种=>语法称为箭头函数,是 JavaScript 的一个相对较新的特性。您将需要一个类似的新版本的 Node 来利用它。

于 2016-04-25T14:36:31.897 回答