如何使用Fastify和NestJS发送文件?

时间:2019-04-27 19:51:55

标签: javascript node.js typescript nestjs fastify

我有以下前端中间件:

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'));
        }
    }
} 

它可以与express一起很好地工作,但与fastify结合,res.sendFileundefined,那么我该如何解决?

2 个答案:

答案 0 :(得分:1)

看看这个issuesendFile在固定方面没有等效的方法;您必须手动进行:

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

答案 1 :(得分:0)

您还可以将index.html存储在内存中并从中发送它:

const bufferIndexHtml = fs.readFileSync(index.html')
res.type('text/html').send(bufferIndexHtml)