简体   繁体   中英

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. It should check first, if robots.txt exists, and if not, create it as before.

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("./"))); , 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:

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:";
        }
  )
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM