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

新手上路,请多包涵

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

原文由 user3700129 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 278
2 个回答

箭头函数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 变量的行为不同。对于这个示例来说无关紧要,但在其他示例中可能会有所不同。)

原文由 CherryDT 发布,翻译遵循 CC BY-SA 3.0 许可协议

升级您的节点版本。

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

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

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

节点兼容性表

原文由 omarjmh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题