| 123 | |
| 124 | // imported from https://github.com/kolodziejczak-sz/uwebsocket-serve |
| 125 | export function serveFile(res /* : HttpResponse */, filepath: string) { |
| 126 | const { size } = statSync(filepath); |
| 127 | const readStream = createReadStream(filepath); |
| 128 | const destroyReadStream = () => !readStream.destroyed && readStream.destroy(); |
| 129 | |
| 130 | const onError = (error: Error) => { |
| 131 | destroyReadStream(); |
| 132 | throw error; |
| 133 | }; |
| 134 | |
| 135 | const onDataChunk = (chunk: Buffer) => { |
| 136 | const arrayBufferChunk = toArrayBuffer(chunk); |
| 137 | |
| 138 | const lastOffset = res.getWriteOffset(); |
| 139 | const [ok, done] = res.tryEnd(arrayBufferChunk, size); |
| 140 | |
| 141 | if (!done && !ok) { |
| 142 | readStream.pause(); |
| 143 | |
| 144 | res.onWritable((offset) => { |
| 145 | const [ok, done] = res.tryEnd( |
| 146 | arrayBufferChunk.slice(offset - lastOffset), |
| 147 | size |
| 148 | ); |
| 149 | |
| 150 | if (!done && ok) { |
| 151 | readStream.resume(); |
| 152 | } |
| 153 | |
| 154 | return ok; |
| 155 | }); |
| 156 | } |
| 157 | }; |
| 158 | |
| 159 | res.onAborted(destroyReadStream); |
| 160 | readStream |
| 161 | .on("data", onDataChunk) |
| 162 | .on("error", onError) |
| 163 | .on("end", destroyReadStream); |
| 164 | } |