Skip to content

Commit

Permalink
feat(file-streaming): add support for range requests in file streaming
Browse files Browse the repository at this point in the history
  • Loading branch information
purocean committed Jan 2, 2025
1 parent 4e0c0c8 commit 5b16b97
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
4 changes: 4 additions & 0 deletions src/main/server/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,10 @@ export function read (repo: string, p: string): Promise<Buffer> {
return withRepo(repo, (_, targetPath) => fs.readFile(targetPath), p)
}

export function createReadStream (repo: string, p: string, options?: Parameters<typeof fs.createReadStream>[1]): Promise<ReturnType<typeof fs.createReadStream>> {
return withRepo(repo, async (_, targetPath) => fs.createReadStream(targetPath, options), p)
}

export function stat (repo: string, p: string) {
return withRepo(repo, async (_, targetPath) => {
const stat = await fs.stat(targetPath)
Expand Down
21 changes: 20 additions & 1 deletion src/main/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,26 @@ const attachment = async (ctx: any, next: any) => {
noCache(ctx)

try {
ctx.body = await file.read(repo, path)
// support range
const range = ctx.headers.range
if (range) {
const { size } = await file.stat(repo, path)
const requestRange = range.replace('bytes=', '').split('-').map((x: string) => parseInt(x || '-1'))
const start = requestRange[0] < 0 ? 0 : requestRange[0]
const end = requestRange[1] < 0
? size - 1
: requestRange[1]

const chunkSize = end - start + 1

ctx.status = 206
ctx.set('Content-Range', `bytes ${start}-${end}/${size}`)
ctx.set('Accept-Ranges', 'bytes')
ctx.set('Content-Length', chunkSize)
ctx.body = await file.createReadStream(repo, path, { start, end })
} else {
ctx.body = await file.read(repo, path)
}
ctx.type = mime.getType(path)
} catch (error: any) {
if (error.code === 'ENOENT') {
Expand Down

0 comments on commit 5b16b97

Please sign in to comment.