MCPcopy Create free account
hub / github.com/MemTensor/MemOS / tryServe

Function tryServe

apps/memos-local-plugin/server/middleware/static.ts:51–94  ·  view source on GitHub ↗
(
  res: ServerResponse,
  root: string,
  relative: string,
)

Source from the content-addressed store, hash-verified

49}
50
51async function tryServe(
52 res: ServerResponse,
53 root: string,
54 relative: string,
55): Promise<boolean> {
56 const resolvedRoot = path.resolve(root);
57 const target = path.resolve(resolvedRoot, "." + relative);
58 if (!target.startsWith(resolvedRoot)) {
59 writeText(res, 403, "forbidden");
60 return true;
61 }
62 try {
63 const st = await stat(target);
64 if (!st.isFile()) {
65 writeNotFound(res);
66 return true;
67 }
68 const ext = path.extname(target).toLowerCase();
69 res.writeHead(200, {
70 "content-type": MIME[ext] ?? "application/octet-stream",
71 "content-length": String(st.size),
72 "cache-control": "public, max-age=60",
73 });
74 // For small files (≤128 KiB) read to buffer and end atomically;
75 // for larger, stream and wait on the response's finish event.
76 if (st.size <= 128 * 1024) {
77 const buf = await readFile(target);
78 res.end(buf);
79 } else {
80 await new Promise<void>((resolve, reject) => {
81 const stream = createReadStream(target);
82 stream.on("error", reject);
83 res.on("finish", () => resolve());
84 res.on("close", () => resolve());
85 stream.pipe(res);
86 });
87 }
88 return true;
89 } catch (err: any) {
90 if (err?.code === "ENOENT") return false; // let the caller write 404
91 writeText(res, 500, "static: " + (err instanceof Error ? err.message : String(err)));
92 return true;
93 }
94}

Callers 1

serveStaticFunction · 0.85

Calls 6

writeTextFunction · 0.85
writeNotFoundFunction · 0.85
resolveFunction · 0.85
resolveMethod · 0.80
endMethod · 0.80
onMethod · 0.65

Tested by

no test coverage detected