Data Chunks in Node.js

Data chunks in Node.js or any other language can be defined as a fragment of data that is sent to all the servers by the client. The servers make a stream of these chunks and form a buffer stream. This buffer stream is then converted into meaningful data.

Syntax

request.on('eventName', [callback] )

Parameters

The parameters are described below −

  • eventName − It is the name of the event that will be fired.

  • callback − Callback function to handle any error if it occurs.

Example

Create a file with the name "index.js" and copy the following code snippet. After creating the file, use the command "node index.js" to run this code.

// Data Chunk Example in Node

// Importing the http module
const http = require('http');

// Creating a server
const server = http.createServer((req, res) => {
   const url = req.url;
   const method = req.method;

   if (url === '/') {
      // Defining the HTML page
      res.write('');
      res.write('Enter Message');
      res.write(`
           
`);       res.write('');       return res.end();    }    // POST Request for sending data    if (url === '/message' && method === 'POST') {       const body = [];       req.on('data', (chunk) => {          // Saving the chunk data at server          body.push(chunk);          console.log(body)       });       req.on('end', () => {          // Parsing the chunk data in buffer          const parsedBody = Buffer.concat(body).toString();          const message = parsedBody.split('=')[1];          // Printing the data          console.log(message);       });       res.statusCode = 302;       res.setHeader('Location', '/');       return res.end();    } }); // Starting the server server.listen(3000);

Output

C:\home\node>> node index.js
[  ]
Welcome+to+Tutorials+Point+%21%21%21

Updated on: 2021-08-18T09:52:53+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements