2016-04-27 48 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缓冲区 –