Skip to content

Commit

Permalink
perf: small improvements (#94)
Browse files Browse the repository at this point in the history
* perf(serve-static): range bytes with limit

* ref: declare and set `start` in one line

* ref: set default `end` value in one line

* perf: don't create reader if writable is destroyed
  • Loading branch information
Yovach authored Nov 13, 2023
1 parent 7f4ba25 commit 3575d60
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 10 deletions.
9 changes: 3 additions & 6 deletions src/serve-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,12 +77,9 @@ export const serveStatic = (options: ServeStaticOptions = { root: '' }): Middlew
c.header('Accept-Ranges', 'bytes')
c.header('Date', stat.birthtime.toUTCString())

let start = 0
let end = stat.size - 1

const parts = range.replace(/bytes=/, '').split('-')
start = parseInt(parts[0], 10)
end = parts[1] ? parseInt(parts[1], 10) : end
const parts = range.replace(/bytes=/, '').split('-', 2)
const start = parts[0] ? parseInt(parts[0], 10) : 0
let end = parts[1] ? parseInt(parts[1], 10) : stat.size - 1
if (size < end - start + 1) {
end = size - 1
}
Expand Down
7 changes: 3 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@ import type { Writable } from 'node:stream'
export function writeFromReadableStream(stream: ReadableStream<Uint8Array>, writable: Writable) {
if (stream.locked) {
throw new TypeError('ReadableStream is locked.')
}
const reader = stream.getReader()
if (writable.destroyed) {
reader.cancel()
} else if (writable.destroyed) {
stream.cancel();
return
}
const reader = stream.getReader()
writable.on('drain', onDrain)
writable.on('close', cancel)
writable.on('error', cancel)
Expand Down

0 comments on commit 3575d60

Please sign in to comment.