ffmpeg-service/server/serve.mjs

34 lines
808 B
JavaScript
Raw Normal View History

2022-05-11 11:09:31 +00:00
import path from 'path'
import { FileResponse } from 'flaska'
import fs from 'fs/promises'
export default class ServeHandler {
constructor(opts = {}) {
Object.assign(this, {
fs: opts.fs || fs,
root: opts.root,
})
}
/** GET: /::file */
serve(ctx) {
let file = path.resolve(path.join(this.root, ctx.params.file ? ctx.params.file : 'index.html'))
if (!file.startsWith(this.root)) {
ctx.status = 404
ctx.body = 'HTTP 404 Error'
return
}
return this.fs.stat(file).catch((err) => {
if (err.code === 'ENOENT') {
file = path.resolve(path.join(this.root, 'index.html'))
return this.fs.stat(file)
}
return Promise.reject(err)
})
.then(function(stat) {
ctx.body = new FileResponse(file, stat)
})
}
}