I'm trying to write a nodejs code that read (audio) files and stream the content to a remote service (dialogflow). I'm having trouble ensuring the order of the chunks sent to the stream. Most of the time everything seems to be in the right order, but once in a while, the data seems to be sent in an out-of-order fashion.
Pseudo code:
for (var i = 0; i < numFiles; ++i) {
await sendData(fs.createReadStream(filenames[i]), i);
}
...
async function sendData(inputDataStream, chunkIndex) {
await inputDataStream
.pipe(new Transform({
objectMode: true,
transform: (obj, _, next) => {
console.log('Sending chunk ' + chunkIndex);
next(null, <some data>);
}
}), {end: false})
.pipe(outputStream, {end: false});
}
I can see that 'Sending chunk ...' is printed out of order sometimes.
Q: is there a way to avoid this problem?
Another issue is that, while, most of the time, each chunk is sent contiguously, occasionally, some chunks will be split and sent in smaller sub-chunks (even though each file is not large). [I repeated this experiment many times on the same set of files]
Q: Is there a way I can control the chunk size? (what did I do wrong here?)
Q: Is this because the remote service cannot handle the rate of transmission? If so, how should I properly react to that?
[I have also tried using pump(), but still observed the same behavior] Thanks in advance.