如何在单个响应中本地响应多个文件给客户端

How to natively response multiple files to client in a single response

我不熟悉服务器端开发,尤其是 node.js,但对于使用多个 .css.js 文件的 Web 应用程序,我需要它。简单的 Web 服务器应该根据客户端请求发送这些文件。我这样做是为了 .html' file, but if I include.jsfiles to.html` 它不会加载到页面。

我认为这是因为应该正确设置响应 headers?或者我应该在服务器端读取我想要响应客户端的每个文件吗?

服务器代码:

var http = require('http');
var fs = require('fs');    

var port = 8080;
var files = ["app.html", "math.js"];        
http.createServer(function(request, response) {

    fs.readFile('app.html', 'utf8', function(err, data) {
        if (err) {
            return console.log(err);
        }

        response.setHeader('Content-type', 'text/html');
        response.end(data);
    });


}).listen(port);

console.log("listening on port: " + port);

app.html 文件

<!doctype html>
<html>
    <head>
        <title>| Demo1</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />


    </head>
    <body>
        <h1>Loaded</h1>
        <h2>Loaded</h2>
        <h3>Loaded</h3>

        <canvas width="700" height="700" id="cnv"></canvas>
        <script type="text/javascript" src="math.js"></script>
    </body>
</html>

p.s. 请不要推荐任何像 express 或模块这样的框架来完成所有的工作。为此,我需要了解如何使用 node.js API。

找到了这个解决方案,我知道它需要编写一些简单的静态 Web 服务器

var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var port = 8080;

var appMainFileName = "app.html";
var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "application/javascript",
    "css": "text/css"
};

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname,
    fileName = path.join(process.cwd(), uri);       

  fs.exists(fileName, function(exists) {
    if (!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(fileName).isDirectory()) {
            fileName += '/' + appMainFileName;
        }

    fs.readFile(fileName, "binary", function(err, data) {
      if (err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200, {"Content-Type": mimeTypes[ fileName.split(".")[1] ]});
      response.write(data, "binary");
      response.end();
    });
  });


}).listen(port);