1

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.

3
  • 1
    Is the css file is generated dynamically, mostly css files will be referred inside html file and you will be serving only an html file Commented Jun 6, 2020 at 15:42
  • 1
    Why are you doing that? Can't you link css directly inside index.html ? Commented Jun 6, 2020 at 15:45
  • did you tried this one stackoverflow.com/questions/28822034/… Commented Jun 6, 2020 at 15:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! This worked like a charm, and I was also able to apply the same format to serve my js files and my site is working now. It makes sense you would want to make the home route async since that one is what would call the other requests to linked style sheets and js files, do I have that right? Also I have noticed a lot of content pushing express over standard node and will be moving that direction but wanted to get some taste of node first.
Yup you can do it in the async await syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.