节点readline模块没有'on'功能? [英] Node readline module doesn't have 'on' function?

查看:101
本文介绍了节点readline模块没有'on'功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用'readline'模块创建一个逐行读取文本文件的节点应用程序,并将其打印到控制台。

I'm trying to create a node app that reads a textfile line by line using the 'readline' module, and prints it to the console.

  var lineReader = require('readline');
  lineReader.createInterface({
    input: fs.createReadStream('./testfile')
  });
  lineReader.on('line', function(line){
    console.log(line);
  });

根据模块的文档,应该有'on'方法。但是当我记录我创建的readline对象的实例时,我在任何地方都看不到'on'方法:

According to the module's documentation, there should be an 'on' method. However when I log the instance of the readline object I created, I don't see an 'on' method anywhere:

{ 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()时,我得到一个e rror说这个功能不存在。

And so, naturally, when I call lineReader.on(), I get an error saying the function doesn't exist.

我正在严格遵循文件......我错过了什么? on方法在哪里?

I'm following the documentation precisely... what am I missing? Where is the on method?

非常感谢您的时间。

推荐答案

继续阅读文档,直到找到上下文的示例

Keep reading the docs until you find 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 方法返回,而不是readline模块本身。

on is a method of the interface returned by the createInterface method, not of the readline module itself.

  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);
  });

这篇关于节点readline模块没有'on'功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆