-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
50 lines (38 loc) · 1.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import fp from 'fastify-plugin'
import { PassThrough } from 'node:stream'
import send from '@fastify/send'
async function send_file_plugin(app) {
const send_file = function (filepath) {
const reply = this
const content_type = `${send.mime.getType(filepath) || send.mime.default_type}; charset=UTF-8`
reply.header('Content-Type', content_type)
const stream = send(reply.request.raw, filepath)
stream.on('error', err => {
if (err.code === 'ENOENT') {
return reply.callNotFound()
}
})
const wrapper = new PassThrough({
flush(cb) {
this.finished = true
cb()
}
})
wrapper.getHeader = reply.getHeader.bind(reply)
wrapper.setHeader = reply.header.bind(reply)
wrapper.removeHeader = () => { }
wrapper.finished = false
Object.defineProperty(wrapper, 'statusCode', {
get: () => reply.raw.statusCode,
set: next => reply.status(next)
})
wrapper.on('pipe', () => {
reply.send(wrapper)
})
stream.pipe(wrapper)
return this
}
app.decorateReply('send_file', send_file)
app.decorateReply('sendFile', send_file)
}
export default fp(send_file_plugin)