-
Notifications
You must be signed in to change notification settings - Fork 2
/
buffer.ts
69 lines (58 loc) · 1.41 KB
/
buffer.ts
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* This example shows how to implement a storage returning NodeJS Buffer
*/
import { Readable } from 'node:stream';
import { fastify } from 'fastify';
import type { StorageInfo, StreamRange } from '../src/send-stream';
import { Storage } from '../src/send-stream';
const app = fastify({ exposeHeadRoutes: true });
class BufferStorage extends Storage<StorageInfo<Buffer>, Buffer> {
// eslint-disable-next-line @typescript-eslint/require-await
async open(data: StorageInfo<Buffer>) {
return {
...data,
size: data.attachedData.byteLength,
};
}
createReadableStream(
storageInfo: StorageInfo<Buffer>,
range: StreamRange | undefined,
autoClose: boolean,
) {
const buffer = range
? storageInfo.attachedData.subarray(range.start, range.end + 1)
: storageInfo.attachedData;
return new Readable({
autoDestroy: autoClose,
read() {
this.push(buffer);
this.push(null);
},
});
}
async close() {
// noop
}
}
const storage = new BufferStorage();
const buf = Buffer.from('data i want to serve', 'utf8');
const mtimeMs = Date.now();
app.get('*', async (request, reply) => {
await storage.send(
{
attachedData: buf,
mtimeMs,
mimeType: 'text/plain',
mimeTypeCharset: 'UTF-8',
},
request.raw,
reply.raw,
);
});
app.listen({ port: 3000 })
.then(() => {
console.info('listening on http://localhost:3000');
})
.catch((err: unknown) => {
console.error(err);
});