端点可以发送字符串、缓冲区或流。
所以onSend 挂钩将接收其中一种数据类型。
例如:
const fastify = require('fastify')()
const fs = require('fs')
const path = require('path')
fastify.addHook('onSend', async (request, reply, payload) => {
console.log(`Payload is a ${payload}`);
return typeof payload
})
fastify.get('/string', (req, reply) => { reply.send('a string') })
fastify.get('/buffer', (req, reply) => { reply.send(Buffer.from('a buffer')) })
fastify.get('/stream', (req, reply) => { reply.send(fs.createReadStream(__filename)) })
fastify.inject('/string', (_, res) => console.log(res.payload))
fastify.inject('/buffer', (_, res) => console.log(res.payload))
fastify.inject('/stream', (_, res) => console.log(res.payload))
fastify-static 将文件作为流发送,因此您需要实现一个转换流。
这是一个快速而肮脏的示例,假设存在一个带有内容的 static/hello 文件:
你好%name
const { Transform } = require('stream')
const fastify = require('fastify')()
const fs = require('fs')
const path = require('path')
const transformation = new Transform({
writableObjectMode: false,
transform(chunk, encoding, done) {
const str = chunk.toString()
this.push(str.replace('%name', 'foo bar'))
done()
}
})
fastify.addHook('onSend', async (request, reply, payload) => {
if (typeof payload.pipe === 'function') {
// check if it is a stream
return payload.pipe(transformation)
}
return payload
})
fastify.register(require('fastify-static'), {
root: path.join(__dirname, 'static'),
prefix: '/static/',
})
fastify.inject('/static/hello', (_, res) => console.log(res.payload))
作为建议,我会使用来自point-of-view 插件的模板系统,因为它支持这些开箱即用的功能。