Home  Tech   Example of ...

Example of The zlib module in Node.js

The zlib module in Node.js is used for data compression and decompression. Compression is a crucial functionality in many applications, especially when dealing with large volumes of data, network communications, and file storage. Here are the key reasons why zlib is important and commonly used in Node.js applications:

1. Reducing Data Size

Use Case:

Example:

2. Improving Network Performance

Use Case:

Example:

3. Efficient Storage

Use Case:

Example:

4. Data Exchange Formats

Use Case:

Example:

5. Stream-Based Compression

Use Case:

Example:

Example Usage of zlib in Node.js

Here are some code examples demonstrating how to use zlib for various tasks:

1. Compressing and Decompressing a String

const zlib = require('zlib');

// Compress a string
const input = 'Hello, this is a sample string to compress!';
zlib.gzip(input, (err, buffer) => {
  if (!err) {
    console.log('Compressed buffer:', buffer);

    // Decompress the buffer
    zlib.gunzip(buffer, (err, output) => {
      if (!err) {
        console.log('Decompressed string:', output.toString());
      } else {
        console.error('Decompression error:', err);
      }
    });
  } else {
    console.error('Compression error:', err);
  }
});

2. Compressing and Decompressing Files

Compress a file:

const fs = require('fs');
const zlib = require('zlib');

const input = fs.createReadStream('input.txt');
const output = fs.createWriteStream('input.txt.gz');

input.pipe(zlib.createGzip()).pipe(output);

Decompress a file:

const fs = require('fs');
const zlib = require('zlib');

const input = fs.createReadStream('input.txt.gz');
const output = fs.createWriteStream('input_decompressed.txt');

input.pipe(zlib.createGunzip()).pipe(output);

3. Enabling Gzip Compression in an Express Server

const express = require('express');
const compression = require('compression');

const app = express();

// Enable gzip compression
app.use(compression());

app.get('/', (req, res) => {
  res.send('Hello, this is a response from the server!');
});

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
Published on: Jun 18, 2024, 01:23 PM  
 

Comments

Add your comment