Skip to content Skip to sidebar Skip to footer

Node.js - Create A New Readstream For A New File, When That File Reaches A Certain Size

Following on from Node - how can i pipe to a new READABLE stream? I am trying to start a new ReadStream for my live-encoded MP3 file when it reaches a certain size (pre-buffering,

Solution 1:

Try this solution, with buffering and writing to file.

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

Post a Comment for "Node.js - Create A New Readstream For A New File, When That File Reaches A Certain Size"