[英]Node.js : Load .js and .css files included in HTML file without Express/frameworks
如何加載與Node.js一起顯示的HTML文件中包含的.js .csv和.css文件? (沒有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正在請求哪些文件,然后修改這些文件的標題(例如.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");
有點農耕,您可能會遇到布線方面的各種問題-但這是個主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.