Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save macchiitaka/4b1c38fc5b2420225c473fa895dabca9 to your computer and use it in GitHub Desktop.
Save macchiitaka/4b1c38fc5b2420225c473fa895dabca9 to your computer and use it in GitHub Desktop.
A method to incrementally download large compressed files in a web browser while simultaneously decompressing and saving them to your computer.
// Add click event listener to a button
document.querySelector('button').addEventListener('click', async () => {
try {
const filename = 'sample.csv.gz';
// Open a file picker dialog and get a handle to the file
const fileHandle = await window.showSaveFilePicker({
suggestedName: filename.slice(0, -'.csv.gz'.length), // Remove .csv.gz extension
types: [
{
description: 'CSV File',
accept: { 'text/csv': ['.csv'] },
},
],
});
// Fetch the compressed file
const response = await fetch('sample.csv.gz');
// Process the file: decompress, decode, and save
await response.body
.pipeThrough(new DecompressionStream('gzip')) // Decompress the gzip stream
.pipeThrough(new TextDecoderStream()) // Decode the decompressed stream to text
.pipeTo(await fileHandle.createWritable()); // Write the decoded text to the file
console.log('File downloaded and saved successfully');
} catch (error) {
console.error('Error downloading or saving file:', error);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment