Reputation: 35
How can you load the .js .csv and .css files included within an HTML file, displayed with Node.js? (Without frameworks like Express)
E.g. <script src="clock.js"></script>
In Firefox, it shows that the page, fs.readFile('./index.html'), is requesting clock.js, jquery.js, etc. as html files, probably because of response.writeHead being text/html.
Is there a way to do:
if file included in index.html = .js
set writeHead to application/javascript
if file included in index.html = .css
set writeHead to text/css
Without specifying in advance what files index.html may include? (e.g. if in the future, index.html also uses menu.js, you wouldn't need to update the node.js script)
Is there a way to see what files are being requested by index.html, then modify the headers of those files (e.g. .js has application/javascript)?
Upvotes: 0
Views: 2025
Reputation: 3441
Is this the sort of thing you are looking for?
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");
A bit agricultural, and you would probably run in to all sort of problems with routing - but its the idea.
Upvotes: 2