How to append to a buffer?

8,288 views
Skip to first unread message

Sean Clark Hess

unread,
Mar 2, 2011, 7:20:24 PM3/2/11
to nodejs
When downloading something over http, it's usually easier to collect
all the data from the request and return it all at once.

For example, if the http request returns a string, you can do
something like this:

request.on('response', function(response) {
var data = ""
response.on('data', function(chunk) {
data += chunk
})

response.on('end', function() {
callback(data)
})
})

How can I do the same thing for binary data? Like, if I'm downloading
an image? I'm using node v0.2.6

Thanks
~sean

Tim Caswell

unread,
Mar 2, 2011, 7:35:25 PM3/2/11
to nod...@googlegroups.com
Buffers can't be resized.  What I often do is collect an array of buffer objects and then at the end, loop over them to get the total size, create a new buffer, and then loop again copying the buffers into their respective slots in the big buffer.


--
You received this message because you are subscribed to the Google Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com.
To unsubscribe from this group, send email to nodejs+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/nodejs?hl=en.


mscdex

unread,
Mar 2, 2011, 7:42:15 PM3/2/11
to nodejs
On Mar 2, 7:20 pm, Sean Clark Hess <seanh...@gmail.com> wrote:
> How can I do the same thing for binary data? Like, if I'm downloading
> an image?  I'm using node v0.2.6

Something like this:

request.on('response', function(res) {
var data = [], dataLen = 0;
res.on('data', function(chunk) {
data.push(chunk);
dataLen += chunk.length;
})
res.on('end', function() {
var buf = new Buffer(dataLen);
for (var i=0,len=data.length,pos=0; i<len; i++) {
data[i].copy(buf, pos);
pos += data[i].length;
}
callback(buf);
})
})

AJ ONeal

unread,
Mar 2, 2011, 8:52:42 PM3/2/11
to nod...@googlegroups.com
Yep


npm install bufferjs

require('bufferjs')

Buffer.concat(arrayOfBuffers);

Sean Clark Hess

unread,
Mar 5, 2011, 2:26:04 PM3/5/11
to nodejs
Cool. Thanks all

On Mar 2, 6:52 pm, AJ ONeal <coola...@gmail.com> wrote:
> Yep
>
> https://github.com/coolaj86/node-bufferjs
>
> npm install bufferjs
>
> require('bufferjs')
>
> Buffer.concat(arrayOfBuffers);
>
> AJ ONeal
> (317) 426-6525
>
>
>
>
>
>
>
> On Wed, Mar 2, 2011 at 5:35 PM, Tim Caswell <t...@creationix.com> wrote:
> > Buffers can't be resized.  What I often do is collect an array of buffer
> > objects and then at the end, loop over them to get the total size, create a
> > new buffer, and then loop again copying the buffers into their respective
> > slots in the big buffer.
>

Xavi

unread,
Apr 16, 2015, 9:14:50 AM4/16/15
to nod...@googlegroups.com
BTW, there's now a `Buffer.concat` built in.
Reply all
Reply to author
Forward
0 new messages