2016-05-18 3 views
0

私はいくつかのMP3データをファイルに書き込むために、ラメパッケージ[1]を使用しています。データはソケット上の生のオーディオとして送信され、受け取ったときにファイルストリームに書き込まれ、10分ごとに新しいファイルに書き込まれます。私が直面している問題は、これが長時間実行されると、ファイルが閉じられていないため、ファイルハンドルが不足しているということです。このようなもの:書き込みが完了したらファイルを閉じる方法は?

var stream; 

var encoder = lame.Encoder({ 
    // Input 
    channels: 2, 
    bitDepth: 16, 
    sampleRate: 44100, 

    // Output 
    bitRate: 128, 
    outSampleRate: 22050, 
    mode: lame.STEREO // STEREO (default), JOINTSTEREO, DUALCHANNEL or MONO 
}); 

encoder.on('data', function(data) { 
    stream.write(data); 
}); 

var server = net.createServer(function(socket) { 
    socket.on('data', function(data) { 

    // There is some logic here that will based on time if it's 
    // time to create a new file. When creating a new file it uses 
    // the following code. 
    stream = fs.createWriteStream(filename); 

    // This will write data through the encoder into the file. 
    encoder.write(data); 

    // Can't close the file here since it might try to write after 
    // it's closed. 
    }); 
}); 

server.listen(port, host); 

ただし、最後のデータチャンクが書き込まれた後にファイルを閉じるにはどうすればよいですか?技術的には、新しいファイルを開くことができますが、前のファイルは最後のチャンクを書き終える必要があります。

このシナリオでは、ファイルを正しく閉じるにはどうすればよいですか?

は、[1] https://www.npmjs.com/package/lame

+0

"データ" は何ですか?読み取り可能なストリームまたはバッファ – KibGzr

+0

@KibGzrこれは 'Buffer'です。 – Luke

答えて

0

次に、あなたのビジネスを解決するためにsocket.ioストリームを使用して読み取り可能なストリームとしてプロセスデータを必要とします。

var ss = require('socket.io-stream'); 

//encoder.on('data', function(data) { 
// stream.write(data); 
//}); 

var server = net.createServer(function(socket) { 
    ss(socket).on('data', function(stream) { 

     // There is some logic here that will based on time if it's 
     // time to create a new file. When creating a new file it uses 
     // the following code. 
     stream.pipe(encoder).pipe(fs.createWriteStream(filename)) 
    }); 
}); 
0

閉じるストリームすべての書き込みが行われた後(ファイル):

stream.end(); 

参照くださいdocumetation:https://nodejs.org/api/stream.html

writable.end([chunk][, encoding][, callback])# 

    * chunk String | Buffer Optional data to write 
    * encoding String The encoding, if chunk is a String 
    * callback Function Optional callback for when the stream is finished 

Call this method when no more data will be written to the stream. If supplied, the 
callback is attached as a listener on the finish event. 
+0

すべての書き込みが完了したと判断するにはどうすればよいですか?エンコーダへの書き込みは非同期です。私。データが書き込まれる前にストリームを閉じるので、 'encoder.write(data)'の後に 'stream.end()'を追加すると失敗します。 – Luke

+0

@ルーク: 'encoder.on( 'end' ..)'? – slebetman

+0

私はおそらく非常によく問題を説明していないでしょう。データはある期間にわたって書き込まれます。特定の 'encoder.end'が起動されることはありません。 50と100の間のデータチャンクが書き込まれている(変化する)画像。 – Luke

関連する問題