0% found this document useful (0 votes)
63 views1 page

Complete NodeJS Streams

The document provides examples of different types of Node.js streams, including Readable, Writable, Duplex, and Transform streams. It demonstrates how to read a file in chunks, write data to a file, create a TCP echo server, and convert input to uppercase. Each example includes code snippets and event handling for various stream operations.

Uploaded by

Somosree Dey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
63 views1 page

Complete NodeJS Streams

The document provides examples of different types of Node.js streams, including Readable, Writable, Duplex, and Transform streams. It demonstrates how to read a file in chunks, write data to a file, create a TCP echo server, and convert input to uppercase. Each example includes code snippets and event handling for various stream operations.

Uploaded by

Somosree Dey
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Complete Node.

js Stream Examples

1. Readable Stream (Read File in Chunks)


const fs = require('fs');
const readStream = fs.createReadStream('input.txt', { encoding: 'utf8', highWaterMark:
16 });
readStream.on('data', (chunk) => { console.log('Received Chunk:', chunk); });
readStream.on('end', () => { console.log('Finished reading file'); });
readStream.on('error', (err) => { console.error('Error:', err); });

2. Writable Stream (Write Data to File)


const fs = require('fs');
const writeStream = fs.createWriteStream('output.txt');
writeStream.write('Hello, this is a writable stream!\n');
writeStream.write('Writing more data...\n');
writeStream.end(() => { console.log('Finished writing to file'); });
writeStream.on('error', (err) => { console.error('Error writing file:', err); });

3. Duplex Stream (TCP Echo Server)


const net = require('net');
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => { console.log('Received:', data.toString());
socket.write('Echo: ' + data); });
socket.on('end', () => { console.log('Client disconnected'); });
});
server.listen(3000, () => { console.log('TCP Server running on port 3000'); });

4. Transform Stream (Convert Input to Uppercase)


const { Transform } = require('stream');
const transformStream = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk.toString().toUpperCase());
callback();
}
});
process.stdin.pipe(transformStream).pipe(process.stdout);

You might also like