node.js - 当新文件达到特定大小时,为新文件创建新的ReadStream

时间:2016-08-02 17:55:27

标签: javascript node.js stream

继续Node - how can i pipe to a new READABLE stream?

我正在尝试使用num_samplesReadStream为我的实时编码的MP3文件创建一个新的fs.watch,当它达到一定的大小时(基本上是缓冲前)。

它可以工作,但是一旦fs.stat开始,我就不知道如何退出观察者并保持流运行。

我已经尝试了如下的承诺,但是永远不会解决,所以重复调用ReadStream

streamEncodedFile

我的另一个可悲的尝试是尝试仅以特定文件大小启动流:

var watcher = fs.watch(mp3RecordingFile);

watcher.on('change', (event, path) => {

  fs.stat(mp3RecordingFile, function (err, stats) {

    if (stats.size > 75533) {

        new Promise(function(resolve, reject) {
                streamEncodedFile(); 
        })
        .then(function(result) {
                watcher.close();
                console.log('watcher closed');
        });

    }

  });
});

function streamEncodedFile() {

  var mp3File = fs.createReadStream(mp3RecordingFile);

            mp3File.on('data', function(buffer){
                io.sockets.emit('audio', { buffer: buffer });
            });

}

1 个答案:

答案 0 :(得分:0)

尝试此解决方案,缓冲并写入文件。

const Writable = require('stream').Writable;
const fs = require('fs');

let mp3File = fs.createWriteStream('path/to/file.mp3');

var buffer = new Buffer([]);
//in bytes
const CHUNK_SIZE = 102400; //100kb

//Proxy for emitting and writing to file
const myWritable = new Writable({
  write(chunk, encoding, callback) {
    buffer = Buffer.concat([buffer, chunk]);
    if(buffer.length >= CHUNK_SIZE) {
       mp3File.write(buffer);
       io.sockets.emit('audio', { buffer: buffer});
       buffer = new Buffer([]);
    }

    callback();
  }
});

myWritable.on('finish', () => {
   //emit final part if there is data to emit
   if(buffer.length) {
       //write final chunk and close fd
       mp3File.end(buffer);
       io.sockets.emit('audio', { buffer: buffer});
   }
});


inbound_stream.pipe(encoder).pipe(myWritable);