Reputation: 14908
I am studying code here of setting up a simple Node server. I have seen and used many times this idiom of saving data chunks in an array and finally concatenating them together.
http.createServer(function(request, response) {
var body = [];
request.on('data', function(chunk) { body.push(chunk); });
request.on('end', function() { body = Buffer.concat(body).toString();
...
What is the type of chunk
? Documentation says it's eitherBuffer
or string
, but which one?
Is it safe to call Buffer.concat(body)
where body
is an array of strings? Documentation of Buffer.concat(list)
says list
should be a list of Buffer instances. Are strings "Buffer instances"?
Upvotes: 4
Views: 3195
Reputation: 203231
The same documentation also states:
The listener callback will be passed the chunk of data as a string if a default encoding has been specified for the stream using the
readable.setEncoding()
method; otherwise the data will be passed as aBuffer
.
Because your code isn't calling setEncoding
, chunk
will be a Buffer.
Is it safe to call
Buffer.concat(body)
wherebody
is an array of strings?
> Buffer.concat(['foo', 'bar', 'xxx'])
TypeError: "list" argument must be an Array of Buffers
So no. But since body
will be an array of Buffer, Buffer.concat(body)
should work just fine.
Upvotes: 10