I'm trying to load an HTML page along with two separate CSS files through http.createServer()'s callback. Here's the important part of the code so far:
var server = http.createServer(function (req, res) {
var htmlData = fs.readFileSync(__dirname + "/public/index.html");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(htmlData);
res.end();
}).listen(port);
When I try to load this, it also tries to load the CSS files linked within the HTML file. I've tried both adding direct links within the header and adding a script within the HTML file to add the links to the header, but neither work. How can I do this without putting the content of the CSS files directly within tags in the HTML file?
You are ignoring the request path and giving it the same file each time.
You need to serve the right file based on the request.
For example: if you want to serve two files index.html and style.css:
var server = http.createServer(function (req, res) {
if (req.url === '/' || req.url === '/index.html') { // respond to both / and /index.html
var htmlData = fs.readFileSync(__dirname + "/public/index.html");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(htmlData);
res.end();
}
else if (req.url === '/style.css') { // respond to /style.css
var cssData = fs.readFileSync(__dirname + "/public/style.css");
res.writeHead(200, { 'Content-Type': 'text/css' });
res.write(cssData);
res.end();
}
}).listen(port);