转换fastify静态服务文件的响应



我使用的是fastify的fastify静态插件,需要转换它提供的文件。例如,我想替换";该链接";用";该链接";。我已经尝试了这里列出的各种fastify.addHook((事件,https://www.fastify.io/docs/latest/Hooks/,而对我来说明智的是";onSend"其中他们演示了[string].replace((,但都失败了。对于onSend处理程序,有效负载不是可变字符串,而是PassThrough可读流。考虑到这一点,我尝试使用payload.on('data', (chunk) => {...})检查数据。这很有见地。我可以看到文件文本,但我有点深入到流和挑剔的插件中,不知道如何继续。

  1. 使用fastify-static时,有没有一种简单的方法可以在发送响应之前转换响应?(为什么文档中的addHook((失败了?(
  2. 假设我正确地将有效载荷解释为可读流,那么在fastify static发送它之前,我如何转换它呢

端点可以发送字符串、缓冲区或流。

因此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将文件作为流发送,因此您需要实现Transform流。这里有一个快速而肮脏的例子,假设存在一个包含内容的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))

作为一个建议,我会从插件的角度使用模板系统,因为它支持开箱即用的这些功能。

最新更新