2017-04-18 58 views
0

我正在嘗試創建一個節點應用程序,它使用'readline'模塊逐行讀取文本文件,並將其打印到控制檯。節點readline模塊沒有'on'功能?

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的對象的實例,我沒有看到一個「上」的方法在任何地方:

{ 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

請繼續閱讀的文檔,直到你找到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的模塊本身。

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

謝謝澄清 – SemperCallide

1

您試圖調用模塊上的方法,而不是對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()方法被調用同一對象上。