Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type of a data chunk in Node http request

Tags:

node.js

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();
  ...
  1. What is the type of chunk? Documentation says it's eitherBuffer or string, but which one?

  2. 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"?

like image 960
kgf3JfUtW Avatar asked Oct 16 '25 14:10

kgf3JfUtW


1 Answers

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 a Buffer.

Because your code isn't calling setEncoding, chunk will be a Buffer.

Is it safe to call Buffer.concat(body) where body 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.

like image 174
robertklep Avatar answered Oct 18 '25 09:10

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!