Ask Your Question
3

What is the procedure for downloading files through Fastify in Nest js?

asked 2023-07-19 21:40:20 +0000

djk gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-07-19 22:07:01 +0000

nofretete gravatar image

To download files through Fastify in NestJS, follow the below steps:

  1. First, install Fastify and Fastify-static npm packages using the following command:
npm install fastify fastify-static
  1. After installing, import FastifyAdapter and fastifyStatic modules from Fastify in your NestJS AppModule:
import { Module } from '@nestjs/common';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import fastifyStatic from 'fastify-static';

@Module({
  imports: [],
})
export class AppModule {}
  1. In the AppModule, create an instance of FastifyAdapter and use its getInstance() method to get the underlying Fastify instance:
@Module({
  imports: [],
})
export class AppModule {
  async configure(app: NestFastifyApplication): Promise<void> {
    const fastifyAdapter = app.get(HttpAdapterHost)?.getInstance() as FastifyAdapter;

    // Define the static assets directory
    fastifyAdapter.register(fastifyStatic, {
      root: path.join(__dirname, '..', '..', 'public'),
    });
  }
}
  1. In your controller, create an endpoint that returns a file:
@Controller('files')
export class FilesController {
  @Get(':filename')
  async downloadFile(
    @Param('filename') filename: string,
  ): Promise<Observable<string>> {
    return of(filename);
  }
}
  1. In the downloadFile method of the controller, return a file stream using Fastify's reply.sendFile() method:
@Controller('files')
export class FilesController {
  @Get(':filename')
  async downloadFile(
    @Param('filename') filename: string,
    @Res() res: FastifyReply,
  ): Promise<void> {
    const filePath = path.join(__dirname, '..', '..', 'public', filename);

    res.type('application/octet-stream'); // Set the content type
    res.sendFile(filePath); // Send the file stream
  }
}
  1. Access the file by making a GET request to the endpoint, passing the filename as a parameter.

That's it! You've successfully downloaded a file through Fastify in NestJS.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-19 21:40:20 +0000

Seen: 12 times

Last updated: Jul 19 '23