stream unzip in javascript

To stream unzip a compressed file in Node.js with JavaScript, we can use the zlib module and fs.createReadStream() to create a readable stream from the compressed file. We will then pipe this to zlib.createUnzip() which will unzip the data. Finally, we create a writable stream to output the contents.

Here's an example of how this can be achieved:

index.tsx
const fs = require('fs');
const zlib = require('zlib');

const zipFilePath = 'compressed.zip';
const outputFilePath = 'uncompressed.txt';

// Create a read stream from the compressed file
const readStream = fs.createReadStream(zipFilePath);

// Create a writable stream to output the contents
const writeStream = fs.createWriteStream(outputFilePath);

// Pipe the read stream to the unzip stream and then to the write stream
readStream.pipe(zlib.createUnzip()).pipe(writeStream);

// Check for any errors during the process
readStream.on('error', (err) => console.log('Error:', err));
writeStream.on('error', (err) => console.log('Error:', err));
647 chars
19 lines

In the above code, we first create a read stream from the compressed file using fs.createReadStream(). We then create a writable stream to output the contents using fs.createWriteStream().

Next, we pipe the read stream to zlib.createUnzip(), which creates an unzip stream. This stream then gets piped to the write stream, which outputs the uncompressed data to outputFilePath.

Finally, we add error handling to the process by handling any errors that may occur during the read and write operations.

gistlibby LogSnag