【问题标题】:Node.js readline: Unexpected token =>Node.js readline:意外的令牌 =>
【发布时间】:2016-08-19 00:30:35
【问题描述】:

我正在学习 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

【问题讨论】:

  • 您使用的是什么版本的节点?可能是不支持 ES6 箭头语法的那个。
  • @CherryDT 刚刚做了。抱歉,社区新手

标签: javascript node.js readline console.readline


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    Arrow functionsECMAScript 6 standard 的新功能之一,仅在version 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 变量的行为不同。对于这个例子来说无关紧要,但在其他例子中可能。)

    【讨论】:

    • 谢谢!这解决了问题。对不起,我没有足够的声誉来投票。我在 Windows 上,版本号是 0.12.2,与 4.0.0 相比,它似乎真的很旧。但我似乎无法通过 npm 升级它(我在 Windows 上并使用了命令“npm install -g n”)。这是为什么呢?
    • 我在旧版本中使用 npm 本身升级也遇到了麻烦,我不确定是什么原因造成的,但我只是下载了latest version from the node.js website 并安装了它。 (与此同时,我转而使用 Chocolatey,这是一个不错的 Windows 包管理器,只需输入 cup nodejs.install 即可升级节点。)
    • 我只是通过choco安装的。效果很好!
    【解决方案3】:

    升级您的节点版本。

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

    检查您使用的是哪个版本node -v

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

    Node Compatibility Table

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-21
        • 2019-08-07
        • 2018-11-10
        • 2013-12-24
        相关资源
        最近更新 更多