Reputation: 117
I am new to node js and trying to simply serve a site containing both an html and css file. I have the below code written
var http = require('http');
var fs = require('fs');
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(fs.readFileSync('./style.css', {encoding: "utf8"}));
res.write(fs.readFileSync('./index.html', {encoding: "utf8"}));
res.end();
}).listen(3000);
console.log('server running @ 3000');
This 'works' when I fire up the server meaning that I can see the site rendering while considering the css, but the css text gets written out at the bottom of my site like its embedded text inside a div tag. Can anyone explain why I am seeing this? Also since I am new to nodejs, any recommendations on serving css or JS files on my server would be greatly appreciated.
Upvotes: 1
Views: 2765
Reputation: 480
I have modified your code (which is working). Have a look at it:
var http = require('http');
var fs = require('fs');
http.createServer((req, res) => {
console.log(req.url)
if (req.url === "/") {
fs.readFile('index.html', (err, html) => {
if (err) {
throw err;
}
res.setHeader('Content-type', 'text/html');
res.write(html);
res.statusCode = 200;
res.end();
});
}
else if (req.url == '/style.css') {
res.setHeader('Content-type', 'text/css');
res.write(fs.readFileSync('style.css'));
res.end();
} else {
res.write("invalid request")
res.end();
}
}).listen(3000);
console.log('server running @ 3000');
Here is the HTML file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="/style.css" />
</head>
<body>
Hello
</body>
</html>
and style.css
body {
color: red;
}
You need to return your files based on your request. For example, in this scenario, the HTML file is requesting the server for /style.css
, the server looks at the code and finds the block which deals with that request
else if (req.url == '/style.css') {
res.setHeader('Content-type', 'text/css');
res.write(fs.readFileSync('style.css'));
res.end();
}
And finally returns the file. I hope that helps.
Recommendation:
Use express.js (https://expressjs.com/). It is really fast minimal and easy to use NodeJS routing framework which follows the MVC pattern. There are lots of resources on youtube and google for this framework.
Upvotes: 2