我正在学习 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 许可协议
箭头函数 是 ECMAScript 6 标准 的新特性之一,仅在 版本 4.0.0 中才被引入 node.js(作为稳定特性)。
您可以升级 node.js 版本或使用旧语法,如下所示:
(请注意,这些语法之间还有一个区别:
this
变量的行为不同。对于这个示例来说无关紧要,但在其他示例中可能会有所不同。)