How to send file with fastify & nestjs?

yantrab picture yantrab · Apr 27, 2019 · Viewed 7.8k times · Source

I have the following front end middleware:

export class FrontendMiddleware implements NestMiddleware {
    use(req: any, res: any, next: () => void) {
        const url = req.originalUrl;
        if (url.indexOf('rest') === 1) {
            next();
        } else if (allowedExt.filter(ext => url.indexOf(ext) > 0).length > 0) {
            res.sendFile(resolvePath(url));
        } else {
            res.sendFile(resolvePath('index.html'));
        }
    }
} 

It works fine with express, but with fastify, res.sendFile is undefined, so how can I fix that?

Answer

Kim Kern picture Kim Kern · Apr 27, 2019

Have a look at this issue. sendFile has no equivalent method in fastify; you have to do it manually:

const stream = fs.createReadStream(resolvePath('index.html'))
res.type('text/html').send(stream)