如何加载 HTML 文件中包含的 .js、.csv 和 .css 文件,并通过 Node.js 显示? (没有像 Express 这样的框架)
例如<script src="clock.js"></script>
在Firefox中,它显示页面fs.readFile('./index.html')正在请求clock.js、jquery.js等作为html文件,可能是因为response.writeHead是text/html。
有没有办法做到:
if file included in index.html = .js
set writeHead to application/javascript
if file included in index.html = .css
set writeHead to text/css
没有提前指定index.html可能包含哪些文件? (例如,如果将来index.html也使用menu.js,则无需更新node.js脚本)
有没有办法查看index.html正在请求哪些文件,然后修改这些文件的 header (例如.js有application/javascript)?
最佳答案
这是您正在寻找的东西吗?
var http = require("http");
var fs = require("fs");
var path = require("path");
var server = http.createServer(function(request, response) {
//typically what will happen here is that you will see
//see the request for the page (index.html?) first and
//then the browser's subsequent requests for js, css etc files
var url = request.url;
var file = //do something clever to extract the file name from the url ( url.split("/")?)
var html = fs.readFileSync(file,"utf-8");
//probably want to check the file extension here to determine the Content-Type
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
});
server.listen(8081);
console.log("Server is listening");
有点农业,你可能会遇到各种路由问题 - 但这是想法。
关于javascript - Node.js : Load . js 和 .css 文件包含在没有 Express/frameworks 的 HTML 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26913513/