写完后如何关闭文件?

时间:2016-05-18 00:56:06

标签: node.js file asynchronous

我正在使用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

2 个答案:

答案 0 :(得分:0)

您需要将流程数据作为可读流,然后使用socket.io-stream来解决您的业务。

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

答案 1 :(得分:0)

完成所有写入后关闭流(文件):

stream.end();

参见文档: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.