koajs / discussions

KoaJS Discussions
2 stars 2 forks source link

ctx.req.on and ctx.req.pipe limitations ? #10

Open vdegenne opened 4 years ago

vdegenne commented 4 years ago

I made a micro web app so I can record my voice anywhere I want. At first I thought it was working perfectly but only to realize the long recordings were trimmed at the end. So I opened up my project again and tried to understand what was going on. I noticed the trimmed recordings had a maximum size of 128K. But the POST data (which is sent in plain format btw) was transmitted by full length. After few experimentation I determined the problem was the piping :

const fileStream = fs.createWriteStream('path/to/file.wav');
ctx.req.pipe(fileStream);

If I change to

const fileData = '';
ctx.req.on('data', function (data) {
  fileData += data;
});
ctx.req.on('end', function () {
  fs.writeFileSync('path/to/file.wav', fileData);
});

It works. But I'd like to understand why the former doesn't wait all the data to be piped in. What do you think ?

Also because I don't like how the latter save all this raw data in the form of a string in a variable before filling up the file container.

Thanks in advance.