[英]How to serve static file if exists, and a file with default values if not exists with koa.js
I want to modify a framework.我想修改一个框架。 At the moment, it creates a
robots.txt
file with default values.目前,它会创建一个具有默认值的
robots.txt
文件。 It should check first, if robots.txt
exists, and if not, create it as before.它应该首先检查
robots.txt
是否存在,如果不存在,则像以前一样创建它。
The code looks like this at the moment:代码现在看起来像这样:
import Koa from "koa";
import { get } from "koa-route";
import serve from "koa-static";
import mount from "koa-mount";
import React from "react";
import { Context } from "@frontity/types";
export default ({ packages }): ReturnType<Koa["callback"]> => {
const app = new Koa();
// Serve static files.
app.use(mount("/static", serve("./build/static")));
// Default robots.txt.
app.use(
get("/robots.txt", (ctx) => {
ctx.type = "text/plain";
ctx.body = "User-agent: *\nDisallow:";
})
);
// Ignore HMR if not in dev mode or old browser open.
const return404 = (ctx: Context) => {
ctx.status = 404;
};
app.use(get("/__webpack_hmr", return404));
app.use(get("/static/([a-z0-9]+\\.hot-update\\.json)", return404));
// Return Frontity favicon for favicon.ico.
app.use(get("/favicon.ico", serve("./")));
// Frontity server rendering.
app.use(async (ctx, next) => {
...
});
return app.callback();
};
I could serve it like favicon.ico
is served: app.use(get("/robots.txt", serve("./")));
我可以像服务
favicon.ico
一样服务它: app.use(get("/robots.txt", serve("./")));
, but I have no idea, how to check it first, if the file exists, and if not return the default value: ,但我不知道如何先检查文件是否存在,如果不存在则返回默认值:
(ctx) => {
ctx.type = "text/plain";
ctx.body = "User-agent: *\nDisallow:";
})
I check the file existence with fs.existsSync
, like:我使用
fs.existsSync
检查文件是否存在,例如:
import fs from "fs";
let hasRobotTxt = false;
if (fs.existsSync("./robots.txt")) {
hasRobotTxt = true;
}
Then serve it conditionally like:然后有条件地提供它,如:
app.use(
get(
"/robots.txt",
hasRobotTxt
? serve("./")
: (ctx) => {
ctx.type = "text/plain";
ctx.body = "User-agent: *\nDisallow:";
}
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.