2016-04-27 6 views
0

Iは、2つの機能INIT データはバッファである(データ)、およびテスト(単語)を、エクスポートのNode.jsモジュールを有します単語は文字列です。読む列ライン

Iは試験()関数内線によってデータバッファインスタンス行から行を読みたいです。

私はNode.jsに経験はありませんが、JSのみです。私はこのスタックからNode.jsモジュールから複数の関数をエクスポートする方法を知っています。

ここまでは関数宣言です。 :

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

    }, 
    test: function(word) { 

    } 
} 

答えて

3

あなたのコメントによると、datainstanceof Bufferであり、それは、1行に1つの英語の単語と辞書が含まれています。したがって、data改行文字で分割して文字列に変換できます。私はそれがより簡単であると思い

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

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

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

module形式で:あなたはtestModule.jsとしてこのコードを保存した場合のように

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; 
}; 

、あなたはメインのコードでは、このモジュールを使用することができます。ありがとう。


(旧答)

私はあなたがreadlineモジュールを使用することができると思います。 しかし、readlineはbufferではなくstreamを受け入れます。 変換する必要があります。例えば。

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バッファ=新しいバッファ(データ)とあなたの答えを使用します。プラス私は引数の使用について何か間違っていると仮定したら私を修正します –

+1

あなたは_data Buffer_をどういう意味ですか? '(バッファのデータインスタンス)=== true'? –

+0

はい、instanceofバッファー –

関連する問題