Home > Web Front-end > JS Tutorial > body text

Streams in Node.js - Tutorial - Part 7

Patricia Arquette
Release: 2024-09-20 20:30:03
Original
409 people have browsed it

Streams in Node.js - Tutorial - Part 7

Understanding Streams in Node.js

Streams in Node.js are a powerful way to handle I/O operations efficiently, especially when working with large amounts of data. Instead of reading and writing data all at once, streams allow us to process it in chunks, which improves performance and reduces memory consumption.

Types of Streams

Node.js provides four types of streams:

Stream Type Description Example
Readable Streams Used for reading data Reading from a file
Writable Streams Used for writing data Writing to a file
Duplex Streams Both readable and writable Sockets
Transform Streams A type of duplex stream where data can be modified as it is read or written Compression
Stream Type

Description

Example

Readable Streams

Used for reading data Reading from a file
    Writable Streams
Used for writing data Writing to a file
Duplex Streams Both readable and writable Sockets
Transform Streams
  • A type of duplex stream where data can be modified as it is read or written Compression
    How Streams Work
  • Streams operate on events, which means they rely on listeners to respond when data is available, ready to be written, or an error occurs. Common events include:
  • data: Emitted when a chunk of data is available.


    end

    : Emitted when there’s no more data to be consumed.
    const fs = require('fs');
    
    const readableStream = fs.createReadStream('example.txt', { encoding: 'utf8' });
    
    readableStream.on('data', (chunk) => {
      console.log('Received chunk:', chunk);
    });
    
    readableStream.on('end', () => {
      console.log('No more data.');
    });
    
    readableStream.on('error', (err) => {
      console.error('Error:', err);
    });
    
    Copy after login

    error: Emitted if any error occurs during the streaming process.


    Readable Stream Example
    const fs = require('fs');
    
    const writableStream = fs.createWriteStream('output.txt');
    
    writableStream.write('Hello, Node.js streams!\n');
    writableStream.end(); // Close the stream
    
    writableStream.on('finish', () => {
      console.log('Finished writing.');
    });
    
    writableStream.on('error', (err) => {
      console.error('Error:', err);
    });
    
    Copy after login

    Let’s look at an example of reading a file using a readable stream:

    Writable Stream Example

    Here’s how you can write to a file using a writable stream:
    • Why Use Streams?
    readableStream.pipe(writableStream);
    
    Copy after login

    Streams help in processing large amounts of data efficiently. For example, when working with files, streams allow you to avoid loading the entire file into memory. This is particularly useful when handling media files, big datasets, or data from HTTP requests.


    Final Tips

    Always handle stream errors using the error event to avoid crashes. Use pipes to easily connect readable streams to writable streams. Streams are perfect for working with I/O-heavy applications, and they make it easier to manage memory when processing large datasets. Thank you for reading, and happy coding! ?

    The above is the detailed content of Streams in Node.js - Tutorial - Part 7. For more information, please follow other related articles on the PHP Chinese website!

    source:dev.to
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Articles by Author
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!