javascript - Node.js 读取行 : Unexpected token =>

标签 javascript node.js readline console.readline

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

最佳答案

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

关于javascript - Node.js 读取行 : Unexpected token =>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36843574/

相关文章:

javascript - 检查对象中是否存在某个元素

javascript - 使用用户模型进行环回时出现 401 错误

javascript - Node js session 覆盖我的第一个 session

javascript - 快速路由——路由到/secrets时出现404错误,我错过了什么

c - 如何在编辑行中追加历史记录?

直接调用readline()的Tab补全

javascript - 如何使用 d3 更新代表 SVG 行的所有数据?

java - GWT 应用程序中出现错误 HTTP 404 ("Script Tag Failure - no status available")

node.js - 使用 或 过滤关键字

javascript - 如何编写与 GNU Emacs 一起使用的 Node.js REPL?