Guide on downloading a zip archive with Archiver and Next.js

Working with Next.js and trying to set up a route for downloading a zip archive that was created using Archiver.

The issue at hand is: how can I pass Archiver to NextResponse?

Check out the code snippet below:

const filesPath = "./data/files/";
const archive = Archiver('zip', { zlib: { level: 9 } });
GetFilesFromKey(token).forEach((filename) => {
    archive.file(filesPath + token + "/" + filename.filename, { name: filename.filename });
});
archive.finalize();

// Need to include the code here that transforms "archive" into "BodyInit"

return new NextResponse(SOME BODY INIT, {
    headers: {
        'Content-Disposition': `attachment; filename="files.zip"`,
        'Content-Type': 'application/octet-stream',
    },
});

Answer №1

Here is the fixed version:

const dataPath = "./data/files/";
const archive = Archiver('zip', { level: 9 });
const stream = new ReadableStream({
    start(ctrl) {
        // Transfer data from the archive to the stream
        archive.on('data', (chunk) => {
            ctrl.enqueue(chunk);
        });

        // Error handling
        archive.on('error', (err) => {
            console.error('Archiver error:', err);
            ctrl.error(err);
        });

        // Close the stream when archiving is complete
        archive.on('end', () => {
            ctrl.close();
        });

        // Add files to the archive
        GetFilesFromKey(token).forEach((filename) => {
            archive.file(dataPath + token + "/" + filename.filename, { name: filename.filename });
        });

        // Finalize the archive
        archive.finalize();
    },
});

return new NextResponse(stream, {
    headers: {
        'Content-Disposition': `attachment; filename="files.zip"`,
        'Content-Type': 'application/octet-stream',
    },
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to comparing two TSX elements in a React + TSX environment

I am facing difficulties in comparing two React TSX elements. Despite being new to both React and TSX, I have tried copying and pasting the exact elements for comparison but it doesn't seem to work. Can you guide me on what might be causing this issue ...

Using NestJS and Mongoose to create a schema with a personalized TypeScript type

I'm struggling to devise a Mongo Schema using nestjs/mongoose decorators based on the structure of the class below: @Schema() export class Constraint { @Prop() reason: string; @Prop() status: Status; @Prop() time: number; } The challeng ...

Revitalize access token with Keycloak in Javascript

I am currently working with keycloak-js version 8.0.1 and have a function called getToken that checks if the token is expired. If it is expired, the function refreshes it; otherwise, it returns the current token. The issue I am facing is that even though t ...

The command "ng test" threw an error due to an unexpected token 'const' being encountered

Any assistance with this matter would be greatly appreciated. I am in the process of constructing an Angular 5 project using angular/cli. The majority of the project has been built without any issues regarding the build or serve commands. However, when a ...

Mongoose version 5.11.14 is causing TypeScript error TS2506 when attempting to utilize async iterators, requiring a '[Symbol.asyncIterator]()' to be present

I have decided to stop using @types/mongoose now that I've discovered that mongoose 5.11 already includes type information. However, when I attempt to run my code through tsc, I encounter TypeScript issues specifically with the following line: for aw ...

Enhancing the appearance of specific text in React/Next.js using custom styling

I have a table and I am currently working on implementing a search functionality that searches for an element and highlights the search terms as they are entered into the search bar. The search function is functional, but I am having trouble with the highl ...

Angular v15 Footer Component Table

In my Angular 15 project, I am attempting to correctly position and utilize the mat table with the following code snippet: <tr mat-footer-row *matFooterRowDef="displayedColumns"></tr>. While the displayedColumns property is functionin ...

How come a Google Maps API component functions properly even without using *NgIf, but fails to work when excluded in Angular 9?

I recently followed the guide provided in this discussion with success. The method outlined worked perfectly for loading search boxes using this component: map.component.html <input id= 'box2' *ngIf="boxReady" class="controls" type="text" p ...

Error TS2559 occurs when the type '{ children: never[]; }' does not share any properties with the type 'IntrinsicAttributes & { post?: IPost | undefined; }'. This discrepancy in properties causes a type mismatch in the code

I'm having trouble understanding what the problem is. I have already looked at answers to this Error here, and I noticed that one of the issues others faced was a repetition of a function name and not giving props to a component in the component tree. ...

Issue with Angular 2: Unable to display 404 error page

I have created a custom "404 - page not found" page to handle situations where the user enters a URL that does not match any paths in my web app: export const routerConfig: Routes = [ { component: LandingPageComponent, path: "", }, { ...

Angular 2's counterparts to jQuery's append(), prepend(), and html() functions

I'm currently working on creating an element through code that looks like this: let template=``; for(let i=0;i<wht.length;i++){ template +=`<li title="${wht[i]}" style="color:#000"> <span (click)="slctRmv($event)"& ...

Transfer a value to the ng2 smart table plugin extension

Upon reviewing the document and source code related to pagination implementation in the (advanced-example-server.component.ts), I discovered that the ServerDataSource being used only supported pagination through HTTP GET (_sort, _limit, _page, etc paramete ...

TypeScript anonymous class-type Higher Order Component (HOC)

Struggling with creating a generic Higher Order Component (HOC) due to type issues. Let's start with a simple example: class Abc extends React.Component<{}> { hello() { } render() { return <View /> } } Referenc ...

Implementation of a recursive stream in fp-ts for paginated API with lazy evaluation

My objective involves making requests to an API for transactions and saving them to a database. The API response is paginated, so I need to read each page and save the transactions in batches. After one request/response cycle, I aim to process the data an ...

Enabling Context Isolation in Electron.js and Next.js with Nextron: A Step-by-Step Guide

I've been working on a desktop application using Nextron (Electron.js + Next.js). Attempting to activate context isolation from BrowserWindow parameters, I have utilized the following code: contextIsolation: true However, it seems that this doesn&ap ...

Getting a value from an object based on a property name in Typescript: A guide to accessing specific

I'm able to accomplish this task using JavaScript const chipColors = { delivered: "success", pending: "warning", canceled: "danger" } <Chip color={chipColors[row.order_status]} <-- This line triggers a Typ ...

Transferring information from one page to the next

How can I efficiently transfer a large amount of user-filled data, including images, between pages in Next.js? I've searched through the Next.js documentation, but haven't found a solution yet. ...

Utilizing Vue class-style components for creating a recursive component

I'm currently working with a class-style component using the vue-property-decorator plugin. I want to create a recursive component that can use itself within its own structure. Here's a snippet of my code: <template> <ul> <li& ...

What happens when you call array.map with 'this' as an argument?

Seeking to understand the binding of 'this' when a function is passed to the map method of an array. Code snippet available on StackBlitz: import './style.css'; class Foo { public method() { return this ? `"this" is a ${this.constr ...

Discovering items located within other items

I am currently attempting to search through an object array in order to find any objects that contain the specific object I am seeking. Once found, I want to assign it to a variable. The interface being used is for an array of countries, each containing i ...