How can you import CSS into a node.js server?

Issue

Say you have a CSS file with the code:

body{
    margin:0px;
}

And the HTML file index.html.
How could you create a server that takes index.html and adds the CSS?
Edit:

var http = require('http');
var fs = require('fs');

function sendFile(res, filename, type) {
    fs.readFile(filename, function(err, data) {
        if (err) {
            console.log(err);
            res.statusCode = 404;
            res.end();
            return
                ;
        }
        res.writeHead(200, { 'Content-Type': type });
        res.write(data);
        res.end();
    });
}

http.createServer(function(req, res) {
    if (req.url == "/") {
        sendFile(res, "index.html", "text/html");
    } 
    else if (req.url == "/styles.css") {
        sendFile(res, "styles.css", "text/css");
    } 
    else {
        res.statusCode = 404;
        res.end();
    }
}).listen(8080);

Solution

This stuff is a lot simpler with a simple framework like Express where you can configure it to automatically serve a directory of static files.

But, if you want to do it yourself using only the built-in http object, you can do something like this:

const http = require('http');
const fs = require('fs');

function sendFile(res, filename, type) {
    fs.readFile(filename, function(err, data) {
        if (err) {
            console.log(err);
            res.statusCode = 404;
            res.end();
            return;
        }
        res.writeHead(200, { 'Content-Type': type });
        res.write(data);
        res.end();
    });
}

http.createServer(function(req, res) {
    if (req.url === "/") {
        sendFile(res, "index.html", "text/html");
    } else if (req.url === "/styles.css") {
        sendFile(res, "styles.css", "text/css");
    } else {
        res.statusCode = 404;
        res.end();
    }
}).listen(8080);

Then, inside of index.html, you can have:

<html>
<head>
<link href="/styles.css"  rel="stylesheet">
</head>
<body>
    <div class="red">This is some text that is supposed to be red</div>
</body>
</html>

In styles.css, you can have:

.red {
    color: red;
}

That will cause the browser to request /styles.css and your web server will be configured to serve that file for that request.

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published