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