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, essentially), by using fs.watch
and fs.stat
.
It works, but once the ReadStream
has started, I don't know how to exit the watcher and keep the stream running.
I've tried a promise as below, but that is never resolved, so streamEncodedFile
is called repeatedly:
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 });
});
}
My other pathetic attempt is to try and start the stream at a certain file size only:
watcher.on('change', (event, path) => {
fs.stat(mp3RecordingFile, function (err, stats) {
console.log(stats.size);
if (stats.size > 75533 && stats.size < 75535) {
streamEncodedFile();
} else if (stats.size > 75535) {
watcher.close();
}
});
});