2016-05-18 29 views
0

我正在使用lame軟件包[1]將一些MP3數據寫入文件。數據在套接字上以原始音頻形式發送,並在接收到數據時寫入文件流,並且每寫入一個新文件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這是一個'緩衝區'。 – 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

@Luke:'encoder.on('end'..)'? – slebetman

+0

我可能沒有很好地解釋這個問題。數據是在一段時間內寫入的。沒有具體的'encoder.end'觸發。圖像表明有50到100個數據塊寫入(它有所不同)。 – Luke

相關問題