Monday, 18 June 2018

node.js Buffers concat is driving me nuts

Hello reddit,i am currently investigating in a bug that is driving me crazy the whole day. Googling, Stackoverflow, every blog says that the Buffer.concat(list, length) function is there to achieve the appending of all buffers to a single one. But all i get after concatenating multiple buffers is the first one.I am fetching small .wav files from a server and try to append them to a single new buffer and send it over to the frontend. Those files are small 2 seconds samples.On the frontend i want to turn that buffer into an AudioBuffer. Which works, but only plays the first buffer of the buffer list.I use node-fetch for that on the express.js backendfetch(url).then(response => response.buffer());I do that for a number of 1-20 files and store those buffers in an array.I checked every buffer in that array and wrote it to a file on the server. Every single file is playable and unique.But if i do thatlet concatedBuffers = Buffer.concat(allBuffers, totalLength);and write that big buffer ( got the size of all buffers combined, still below 5 MB) to a file, it only represents the first buffer item.I tried to use a library for buffer concat, i even wrote an implementation. But still the same result. Only the first buffer is there after appending.Does someone have a clue and can point out my misleading understanding of Buffers, please?The implementation ( copied from buffer-concat library):function concatenateBuffers( list, length? ){let size = 0;if (!Array.isArray(list)){throw new Error('Usage: concatenateBuffers(list, [length])');}if (list.length === 0){return new Buffer(0);} else if (list.length === 1){return list[0];}if (typeof length !== 'number'){size = 0;for (let i = 0; i < list.length; i++){let buf = list[i];size += buf.length;}console.log('calculated Size: ', size);} else {size = length;}let buffer = new Buffer(size);let pos = 0;for (let i = 0; i < list.length; i++){let buf = list[i];buf.copy(buffer, pos);pos += buf.length;}return buffer;}

Submitted June 18, 2018 at 02:28PM by drdrero

No comments:

Post a Comment