Jack Garay Jack Garay - 2 years ago 146
Node.js Question

NodeJS Http.get() Concatenate Data

This is somehow a basic question but there's really less nodeJS references available. Why does: the line:

data += data


data = data

From the below code matter? The first one produces twice the actual content of the file provided in the options object, while the latter produces the weird buffer output.

http.get(options, (response) => {

response.on("data", (data) => {
data += data;

response.on("error", () => {
console.log("An error has occured. Bummer.");

Answer Source

The first one (data += data) appends data to data, and because of the += an implicit conversion from Buffer to String is done, because of that you see a string as output for console.log(data);.

The second one (data = data) just assigns data to data, so it does nothing at all. Because of that the type of data does not change and is still Buffer

If you want to log the content of a buffer as string you would need to buf.toString: console.log(data.toString())

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download