In Node.js, you can use the built-in zlib
module to compress and decompress files using various compression algorithms. Here's a simple example demonstrating how to compress a file using gzip compression:
const fs = require('fs');
const zlib = require('zlib');
const inputFilePath = 'example.txt';
const outputFilePath = 'example.txt.gz';
const compressFile = (inputPath, outputPath) => {
const readStream = fs.createReadStream(inputPath);
const writeStream = fs.createWriteStream(outputPath);
const gzip = zlib.createGzip();
// Pipe the read stream through gzip and then to the write stream
readStream.pipe(gzip).pipe(writeStream);
writeStream.on('finish', () => {
console.log('File compressed successfully.');
});
};
compressFile(inputFilePath, outputFilePath);
In this example:
- The
fs.createReadStream
method creates a readable stream from the input file (example.txt
). - The
zlib.createGzip
method creates a gzip transform stream. - The
fs.createWriteStream
method creates a writable stream for the output file (example.txt.gz
). - The
pipe
method is used to pipe the data from the read stream through the gzip transform stream and then to the write stream.
After running this script, you'll have a compressed file (example.txt.gz
) in the same directory as your script.
Remember to handle errors appropriately, for example, by listening to the 'error' events on the streams:
readStream.on('error', (err) => {
console.error(`Error reading stream: ${err.message}`);
});
gzip.on('error', (err) => {
console.error(`Error compressing stream: ${err.message}`);
});
writeStream.on('error', (err) => {
console.error(`Error writing compressed stream: ${err.message}`);
});
This script uses gzip compression, but you can also use other compression algorithms provided by the zlib
module, such as zlib.createDeflate
or zlib.createBrotliCompress
, depending on your requirements and the availability of algorithms on your system.