1 | initial version |
To download files through Fastify in NestJS, follow the below steps:
npm install fastify fastify-static
import { Module } from '@nestjs/common';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import fastifyStatic from 'fastify-static';
@Module({
imports: [],
})
export class AppModule {}
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'),
});
}
}
@Controller('files')
export class FilesController {
@Get(':filename')
async downloadFile(
@Param('filename') filename: string,
): Promise<Observable<string>> {
return of(filename);
}
}
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
}
}
That's it! You've successfully downloaded a file through Fastify in NestJS.