Node.js Tutorial
- Node.js Tutorial
- Install Node.js on Windows
- Install Node.js on Linux/Ubuntu/CentOS
- Node.js First Example
- Node.js Console
- Node.js REPL
- Node.js Package Manager
- Node.js Command Line Options
- Node.js Global Objects
- Node.js OS
- Node.js Timer
- Node.js Errors
- Node.js DNS
- Node.js Net
- Node.js Crypto
- Node.js TLS/SSL
- Node.js Debugger
- Node.js Process
- Node.js Child Process
- Node.js Buffers
- Node.js Streams
- Node.js File System (FS)
- Node.js Path
- Node.js StringDecoder
- Node.js Query String
- Node.js ZLIB
- Node.js Assertion Testing
- Node.js V8
- Node.js Callbacks
- Node.js Events
- Node.js Punycode
- Node.js TTY
- Node.js Web Module
- NestJS
Node.js MySQL
Node.js MongoDB
Nodejs Difference
Node.js MCQ
Node.js Express
Nodejs Interview Questions
Node.js ZLIB
The Node.js Zlib module is used to provide compression and decompression (zip and unzip) functionalities. It is implemented using Gzip and deflate/inflate.
The zlib module can be accessed using:
- const zlib = require('zlib');
Compressing and decompressing a file can be done by piping the source stream data into a destination stream through zlib stream.
Node.js ZLIB Example: Compress File
Let's see a simple example of Node.js ZLIB module to compress a file "input.txt" into "input.txt.gz".
File: zlib_example1.js
- const zlib = require('zlib');
- const gzip = zlib.createGzip();
- const fs = require('fs');
- const inp = fs.createReadStream('input.txt');
- const out = fs.createWriteStream('input.txt.gz');
- inp.pipe(gzip).pipe(out);
We have a text file named "input.txt" on the desktop.
Open Node.js command prompt and run the following code:
- node zlib_example1.js
You can see that it will produce a compressed file named "input.txt.gz" on the desktop.
Node.js ZLIB Example: Decompress File
Let's see a simple example of Node.js ZLIB module to decompress a file "input.txt.gz" into "input2.txt".
File: zlib_example2.js
- const zlib = require('zlib');
- const unzip = zlib.createUnzip();
- const fs = require('fs');
- const inp = fs.createReadStream('input.txt.gz');
- const out = fs.createWriteStream('input2.txt');
- inp.pipe(unzip).pipe(out);
- node zlib_example2.js
Now you will see that same code of "input.txt" is available into "input2.txt" file.