2016-04-27 30 views
0

我有一個Node.js的模塊,其導出兩個函數初始化(數據),其中數據是緩衝液,和測試(字),其中單詞是一個字符串。讀串線通過的Node.js模塊自緩衝區實例線

我想從行讀取數據緩衝區實例行內測試()函數。

我沒有Node.js的經驗,只有JS。我從這個堆棧中知道的是如何從Node.js模塊中導出多個函數。

到目前爲止,這裏是函數聲明。 :

module.exports = { 
    init: function(data) { 

    }, 
    test: function(word) { 

    } 
} 

回答

3

根據您的意見,datainstanceof Buffer,它包含每行一個英文單詞的字典。所以,現在您可以將data轉換爲字符串數組,分割新行個字符。與module格式:

module.exports.init = function (data) { 
    if (!(data instanceof Buffer)) { 
     throw new Error('not a instanceof Buffer'); 
    } 
    this.currentData = data.toString().split(/(?:\r\n|\r|\n)/g); 
}; 

module.exports.test = function (word) { 
    // for example 
    var yourTestMethod = function (lineNumber, lineContent, testWord) { 
     return true; 
    }; 
    if (this.currentData && this.currentData.length) { 
     for (var line = 0; line < this.currentData.length; line++) { 
      if (yourTestMethod(line, this.currentData[line], word)) { 
       return true; 
      } 
     } 
    } 
    return false; 
}; 

,如果你將這段代碼保存爲testModule.js,你可以使用這個模塊中的主要代碼如下:

// load module 
var testModule = require('./testModule.js'); 

// init 
var buf = new Buffer(/* load dictionaly */); 
testModule.init(buf); 

// test 
console.log(testModule.test('foo')); 

我覺得是比較簡單的。謝謝。


(舊答案)

我認爲你可以使用readline模塊。 但是,readline接受stream,而不是buffer。 所以它需要轉換。例如。

var readline = require('readline'); 
var stream = require('stream'); 

// string to buffer 
var baseText = 'this is a sample text\n(empty lines ...)\n\n\n\nend line:)'; 
var buf = new Buffer(baseText); 

// http://stackoverflow.com/questions/16038705/how-to-wrap-a-buffer-as-a-stream2-readable-stream 
var bufferStream = new stream.PassThrough(); 
bufferStream.end(buf); 

var rl = readline.createInterface({ 
    input: bufferStream, 
}); 

var count = 0; 
rl.on('line', function (line) { 
    console.log('this is ' + (++count) + ' line, content = ' + line); 
}); 

則輸出爲:

> node test.js 
this is 1 line, content = this is a sample text 
this is 2 line, content = (empty lines ...) 
this is 3 line, content = 
this is 4 line, content = 
this is 5 line, content = 
this is 6 line, content = end line:) 

怎麼會這樣?

+0

請檢查我的問題和答案如何使用測試函數內的數據變量,以便我可以做這樣的事情var buffer = new Buffer(data)並使用你的答案。另外糾正我,如果我假設任何錯誤的論點使用 –

+1

你是什麼意思_data Buffer_? '(數據instanceof緩衝區)===真'? –

+0

是的,instanceof緩衝區 –