File watching and various tweaks

This commit is contained in:
Zef Hemel
2022-02-25 15:34:00 +01:00
parent 0527430626
commit 2986c2c231
21 changed files with 264 additions and 119 deletions
+19 -6
View File
@@ -6,24 +6,31 @@ import { oakCors } from "https://deno.land/x/cors@v1.2.0/mod.ts";
import { readAll } from "https://deno.land/std@0.126.0/streams/mod.ts";
import { exists } from "https://deno.land/std@0.126.0/fs/mod.ts";
type NuggetMeta = {
name: string;
lastModified: number;
};
const fsPrefix = "/fs";
const nuggetsPath = "../nuggets";
const fsRouter = new Router();
fsRouter.use(oakCors());
fsRouter.use(oakCors({ methods: ["OPTIONS", "GET", "PUT", "POST"] }));
fsRouter.get("/", async (context) => {
const localPath = nuggetsPath;
let fileNames: string[] = [];
let fileNames: NuggetMeta[] = [];
for await (const dirEntry of Deno.readDir(localPath)) {
if (dirEntry.isFile) {
fileNames.push(
dirEntry.name.substring(
const stat = await Deno.stat(`${localPath}/${dirEntry.name}`);
fileNames.push({
name: dirEntry.name.substring(
0,
dirEntry.name.length - path.extname(dirEntry.name).length
)
);
),
lastModified: stat.mtime?.getTime()!,
});
}
}
context.response.body = JSON.stringify(fileNames);
@@ -33,7 +40,9 @@ fsRouter.get("/:nugget", async (context) => {
const nuggetName = context.params.nugget;
const localPath = `${nuggetsPath}/${nuggetName}.md`;
try {
const stat = await Deno.stat(localPath);
const text = await Deno.readTextFile(localPath);
context.response.headers.set("Last-Modified", "" + stat.mtime?.getTime());
context.response.body = text;
} catch (e) {
context.response.status = 404;
@@ -46,7 +55,9 @@ fsRouter.options("/:nugget", async (context) => {
try {
const stat = await Deno.stat(localPath);
context.response.headers.set("Content-length", `${stat.size}`);
context.response.headers.set("Last-Modified", "" + stat.mtime?.getTime());
} catch (e) {
// For CORS
context.response.status = 200;
context.response.body = "";
}
@@ -69,8 +80,10 @@ fsRouter.put("/:nugget", async (context) => {
const text = await readAll(result.value);
file.write(text);
file.close();
const stat = await Deno.stat(localPath);
console.log("Wrote to", localPath);
context.response.status = existingNugget ? 200 : 201;
context.response.headers.set("Last-Modified", "" + stat.mtime?.getTime());
context.response.body = "OK";
});