How Chunks Work
Chunks are essential for streaming data efficiently. When data is read from a stream, it is divided into chunks and processed piece by piece. Similarly, when writing data to a stream, data is sent in chunks. This chunked approach is particularly useful for applications such as file processing, video streaming, and real-time data transfer.
Syntax:
request.on('eventName',callback)
Parameters
- eventName: It is the name of the event that fired
- callback: It is the Callback function i.e Event handler of the particular event.
Return type
The return type of this method is void.
Example: Implementation to show the chunk form in nodejs
// index.js
// Importing http libraries
const http = require('http');
// Creating a server
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
if (url === '/') {
// Sending the response
res.write('<html>');
res.write('<head><title>Enter Message</title><head>');
res.write(`<body><form action="/message" method="POST">
<input type="text" name="message"></input>
<button type="submit">Send</button></form></body></html>`);
res.write('</html>');
return res.end();
}
// Handling different routes for different type request
if (url === '/message' && method === 'POST') {
const body = [];
req.on('data', (chunk) => {
// Storing the chunk data
body.push(chunk);
console.log(body)
});
req.on('end', () => {
// Parsing the chunk data
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);
Step to Run Application: Run the application using the following command from the root directory of the project
node index.js
Output: Your project will be shown in the URL http://localhost:3000/
Console Output:
What is Chunk in Node.js ?
In Node.js, the term “chunk” refers to a small, manageable piece of data that is part of a larger dataset. Node.js processes data in chunks, especially when dealing with streams, which makes handling large files or data sources more efficient and memory-friendly. This article explores what chunks are, how they work, and their significance in Node.js.