我正在尝试创建一个 Node 应用程序,它使用“readline”模块逐行读取文本文件,并将其打印到控制台。
var lineReader = require('readline');
lineReader.createInterface({
input: fs.createReadStream('./testfile')
});
lineReader.on('line', function(line){
console.log(line);
});
根据模块的文档,there should be an 'on' method .但是,当我记录我创建的 readline 对象的实例时,我在任何地方都看不到“on”方法:
{ createInterface: [Function], Interface: { [Function: Interface]
super_:
{ [Function: EventEmitter]
EventEmitter: [Circular],
usingDomains: false,
defaultMaxListeners: [Getter/Setter],
init: [Function],
listenerCount: [Function] } },
emitKeypressEvents: [Function: emitKeypressEvents],
cursorTo: [Function: cursorTo],
moveCursor: [Function: moveCursor],
clearLine: [Function: clearLine],
clearScreenDown: [Function: clearScreenDown],
codePointAt: [Function: deprecated],
getStringWidth: [Function: deprecated],
isFullWidthCodePoint: [Function: deprecated],
stripVTControlCharacters: [Function: deprecated] }
因此,很自然地,当我调用 lineReader.on()
时,我收到一条错误消息,指出该函数不存在。
我严格按照文档操作...我错过了什么? on 方法在哪里?
非常感谢您抽出时间。
最佳答案
继续阅读文档,直到找到 an example with context :
var readline = require('readline'), rl = readline.createInterface(process.stdin, process.stdout); rl.setPrompt('OHAI> '); rl.prompt(); rl.on('line', function(line) { switch(line.trim()) { // …
on
是 createInterface
方法返回的 interface 的方法,而不是 readline 模块本身的方法。
var lineReader = require('readline');
// You need to capture the return value here
var foo = lineReader.createInterface({
input: fs.createReadStream('./testfile')
});
// … and then use **that**
foo.on('line', function(line){
console.log(line);
});
关于javascript - Node readline 模块没有 'on' 功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43473537/