节点readline模块没有'on'功能?

时间:2017-04-18 13:24:50

标签: javascript node.js methods module filereader

我正在尝试使用'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方法在哪里?

非常感谢您的时间。

2 个答案:

答案 0 :(得分:3)

继续阅读文档,直至找到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方法返回的接口的方法,而不是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);
  });

答案 1 :(得分:2)

您正尝试在模块上调用方法,而不是createInterface()

的结果

而不是:

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

试试这个:

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

请参阅http://node.readthedocs.io/en/latest/api/readline/

上的文档

示例:

var readline = require('readline'),
    rl = readline.createInterface(process.stdin, process.stdout);

rl.setPrompt('OHAI> ');
rl.prompt();

rl.on('line', function(line) {
  switch(line.trim()) {
    case 'hello':
      console.log('world!');
      break;
    default:
      console.log('Say what? I might have heard `' + line.trim() + '`');
      break;
  }
  rl.prompt();
}).on('close', function() {
  console.log('Have a great day!');
  process.exit(0);
});

正如您所看到的,调用.on()的结果调用.createInterface() - 而不是调用.createInterface()方法的同一对象。