Node JS - Buffer



Buffer is a type of memory, which used to hold the binary data type. When any data transmission takes place from client to server, the content gets converted into the binary form and stored in the buffer memory.

Buffer is suitable for small data size transmission, as keeping huge amount of data in memory will be an optimization issue.

Example :

//Buffer load the entire data into a buffer memory,
// It is not suitable for large data transmission
const fs = require("fs");
const http = require("http");

http
  .createServer((reqres=> {
    fs.readFile(__filename, (errdata=> {
      console.log(data); //<Buffer 2f 2f 42 75 66 66 65 72 20 6c 6f 61 64 20 74 68 65 20 65 6e 74 69 72 65 20 64 61 74 61 20 69 6e 74 6f 20 61 20 62 75 66 66 65 72 20 6d 65 6d 6f 72 79 ... 372 more bytes>
      res.writeHeader(200, { "Content-Type": "text/html" });
      res.end(data);
    });
  })
  .listen(3000, () => console.log("Connected!!"));