javascript - Node readline 模块没有 'on' 功能?

标签 javascript node.js methods module filereader

我正在尝试创建一个 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()) {
  // …

oncreateInterface 方法返回的 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/

相关文章:

javascript - 谷歌地图 Javascript 用多边形制作路径

javascript - 动态添加的输入框不是动态绑定(bind)的

java - Java 中的钩子(Hook)和抽象方法的区别

java - 如何调用带参数的方法?

javascript - 在angularjs中缓存图像 - ngRepeat

javascript - 同一类的 JQuery 不同内容

node.js - Mongoose:使用带有限制的 $in 运算符

javascript - 关于 AngularJS 中的异步、 promise 和链接的问题

javascript - 在 Async/Await 中包装 FTP 请求

java - 如何创建方法来生成新的 LinkedList?