2016-05-18 78 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