使用koa.js显示静态html文件

Display a static html file with koa.js

本文关键字:html 文件 静态 显示 koa js 使用      更新时间:2023-09-26

我想做的是服务index.html文件时,索引路由(即localhost:3000)被调用。

我使用koa-router路由,所以我的路由看起来像这样:

app.all("/", function * (next){
    //Send the file here
});

我尝试像这样使用koa-static:

var serve = require('koa-static');
 app.all("/", function * (next){
        serve("index.html");
    });

但这不起作用。然后我尝试使用协同视图(我现在把html文件放在公共目录中):

var views = require("co-views");
var render = views("public");
app.all("/", function * (next){
    this.status = 200;
    this.body = yield render("index.html");
});

但是没有成功。

谁能告诉我该怎么做?

有几种方法可以做到这一点,这里有两种方法。

模板引擎

最简单的方法可能是使用像swig或jade这样的模板引擎来提供文件。

安装命令:

npm install -s swig

如果要使用共视图,只需执行

var views = require("co-views");
var render = views("public", { map: { html: 'swig' });
app.all("/", function * (next){
  this.body = yield render("index");
}); 

普通文件系统

或者如果你不想使用模板引擎,你可以使用普通的Node文件系统库。

为了能够与yield一起使用它,您必须将函数包装在promise中。

var fs = require('fs');
var readFileThunk = function(src) {
  return new Promise(function (resolve, reject) {
    fs.readFile(src, {'encoding': 'utf8'}, function (err, data) {
      if(err) return reject(err);
      resolve(data);
    });
  });
}
app.use(router.get('/', function *(){
  this.body = yield readFileThunk(__dirname + '/public/htmlfilename.html');
}));

另外,请注意,如果使用koa-static,并将index.html放在公用文件夹(链接到koa-static的文件夹)中,默认情况下,它将在根url上提供index.html,而不需要任何代码。

向koa主体传递文件流

这与上面使用普通文件系统的解决方案非常相似,但它利用了koa能力来传递可读流作为响应体。因此,我们唯一需要做的就是打开一个文件的可读流,并将其传递给上下文体。在此之前,给koa一个提示,这是html类型的响应。

import { createReadStream } from 'fs';
public async handle(ctx, next) {
    ctx.type = 'html';
    ctx.body = createReadStream('index.html');
}

使用koa-static

app.all("/", async(ctx, next) => 
  serve(`${__dirname}/public`)(
    Object.assign(ctx, { path: 'index.html' }), 
    next)
  );