如何在静态文件存在的情况下提供服务,如果不存在,如何用koa.js提供一个默认值的文件?

问题描述 投票:0回答:1

我想修改一个框架。目前,它创建了一个 robots.txt 文件的默认值。它应该首先检查,如果 robots.txt 存在,如果不存在,就像之前一样创建它。

目前的代码是这样的。

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();
};

我可以把它当作 favicon.ico 是服务。app.use(get("/robots.txt", serve("./")));但我不知道,如何检查它首先, 如果文件存在,如果没有返回默认值。

(ctx) => {
  ctx.type = "text/plain";
  ctx.body = "User-agent: *\nDisallow:";
})
javascript node.js koa
1个回答
0
投票

我检查文件是否存在,用 fs.existsSync,像。

import fs from "fs";

let hasRobotTxt = false;
if (fs.existsSync("./robots.txt")) {
  hasRobotTxt = true;
}

那就有条件地提供服务,比如:

app.use(
  get(
    "/robots.txt",
    hasRobotTxt
      ? serve("./")
      : (ctx) => {
          ctx.type = "text/plain";
          ctx.body = "User-agent: *\nDisallow:";
        }
  )
);
© www.soinside.com 2019 - 2024. All rights reserved.