从Node.js模块中的Buffer实例逐行读取字符串

Div*_*mmy 2 javascript node.js

我有一个Node.js模块,它导出两个函数init(data),其中数据是Buffer,而test(word),其中word是一个字符串.

我想在test()函数中逐行读取数据Buffer实例中的行.

我没有Node.js的经验,只有JS.我从这个堆栈中了解到的是如何从Node.js模块中导出多个函数.

到目前为止这是函数声明.:

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

    },
    test: function(word) {

    }
}
Run Code Online (Sandbox Code Playgroud)

rio*_*ami 6

根据你的评论,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;
};
Run Code Online (Sandbox Code Playgroud)

如果将此代码保存为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'));
Run Code Online (Sandbox Code Playgroud)

我认为这更简单.谢谢.


(老回答)

我想你可以使用readline模块.但是readline接受a stream,而不是a 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);
});
Run Code Online (Sandbox Code Playgroud)

然后输出是:

> 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:)
Run Code Online (Sandbox Code Playgroud)

那个怎么样?