MCPcopy Create free account
hub / github.com/denoland/std / serveFile

Function serveFile

http/file_server.ts:183–338  ·  view source on GitHub ↗
(
  req: Request,
  filePath: string,
  options?: ServeFileOptions,
)

Source from the content-addressed store, hash-verified

181 * @returns A response for the request.
182 */
183export async function serveFile(
184 req: Request,
185 filePath: string,
186 options?: ServeFileOptions,
187): Promise<Response> {
188 await req.body?.cancel();
189
190 if (req.method !== METHOD.Get && req.method !== METHOD.Head) {
191 return createStandardResponse(STATUS_CODE.MethodNotAllowed);
192 }
193
194 let { etagAlgorithm: algorithm = "SHA-256", fileInfo } = options ?? {};
195
196 try {
197 fileInfo ??= await Deno.stat(filePath);
198 } catch (error) {
199 if (error instanceof Deno.errors.NotFound) {
200 return createStandardResponse(STATUS_CODE.NotFound);
201 } else {
202 throw error;
203 }
204 }
205
206 if (fileInfo.isDirectory) {
207 return createStandardResponse(STATUS_CODE.NotFound);
208 }
209
210 const headers = createBaseHeaders();
211
212 const etag = fileInfo.mtime
213 ? await eTag(fileInfo, { algorithm })
214 : await HASHED_DENO_DEPLOYMENT_ID;
215
216 // Set last modified header if last modification timestamp is available
217 if (fileInfo.mtime) {
218 headers.set(HEADER.LastModified, fileInfo.mtime.toUTCString());
219 }
220 if (etag) {
221 headers.set(HEADER.ETag, etag);
222 }
223
224 // Set mime-type using the file extension in filePath
225 const contentTypeValue = contentType(extname(filePath));
226 if (contentTypeValue) {
227 headers.set(HEADER.ContentType, contentTypeValue);
228 }
229 const fileSize = fileInfo.size;
230
231 if (req.method === METHOD.Head) {
232 // Set content length
233 headers.set(HEADER.ContentLength, `${fileSize}`);
234
235 const status = STATUS_CODE.OK;
236 return new Response(null, {
237 status,
238 statusText: STATUS_TEXT[status],
239 headers,
240 });

Callers 3

createServeDirResponseFunction · 0.70

Calls 14

eTagFunction · 0.90
extnameFunction · 0.90
ifNoneMatchFunction · 0.90
createStandardResponseFunction · 0.85
createBaseHeadersFunction · 0.85
contentTypeFunction · 0.85
parseRangeHeaderFunction · 0.85
maxMethod · 0.80
minMethod · 0.80
seekMethod · 0.80
statMethod · 0.65
setMethod · 0.65

Tested by

no test coverage detected