Stream and Buffers

Streams and buffers are two important concepts in Node.js for handling data in an efficient and scalable way.

A stream is a sequence of data chunks that can be read from or written to. Streams are useful for working with large amounts of data, such as reading data from a file or processing incoming network data, because they allow you to read or write data in small chunks, instead of loading the entire data into memory at once. In Node.js, streams can be either readable, writable, or both.

A buffer is a region of memory used to temporarily store data. Buffers in Node.js are similar to arrays, but have different memory management and can store binary data, not just strings. In Node.js, you can use buffers to store data that you read from or write to a stream.

Here's an example of how you could use streams and buffers to read data from a file:

const fs = require('fs');
const stream = fs.createReadStream('file.txt');

stream.on('data', (chunk) => {
  console.log(chunk.toString());
});

stream.on('end', () => {
  console.log('Finished reading file');
});

In this example, the fs module is used to create a readable stream for the file file.txt. The data event is emitted whenever a chunk of data is available to be read, and the end event is emitted when the entire file has been read. In the event handler for the data event, the chunk of data is logged to the console after being converted to a string using the toString() method.

This is just a simple example of how you can use streams and buffers in Node.js.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    const url = req.url;
    if (url === '/') {
        return res.end(
            `<h1>Input <h1/>  
        <form action="/message" method="POST"> 
        <input name="message"/>
        <button type="submit">Submit</button>
        </form>`
        )
    }

    if (url === '/message' && req.method == "POST") {

        const body = [];

        req.on('data', (chunk) => {
            body.push(chunk);
        });

        req.on('end', () => {
            const parsedData = Buffer.concat(body).toString();
            console.log(parsedData.split("=")[1]);
        });

        res.end("ok");




    }


    if (url === '/message' && req.method == "GET") {
        return res.end(
            `<h1>Input <h1/>  
        <form action="/message" method="POST"> 
        <input name="message"/>
        <button type="submit">Submit</button>
        </form>`
        )
    }

});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Last updated