M
M
MaksN92022-02-21 13:10:54
Node.js
MaksN9, 2022-02-21 13:10:54

How to connect html and css files to the server on node.js?

How to connect html and css files to a node.js server without using Express, Nest, Hapi?

Here's what I wrote, but I think it's not correct.

let http = require('http');
let fs = require('fs');
let path = require('path');

http.createServer(function(req, res){
    if(req.url === "/"){
        fs.readFile('index.html', null, function(err, html){
            res.writeHead(200, {"Content-Type": "text/html"});
            res.end(html);
            });
    }
    else if(req.url.match('style.css')){
        var cssPath = path.join(__dirname, req.url);
        var fileStream = fs.createReadStream(cssPath);
        res.writeHead(200, {"Content-Type": "text/css"});
        fileStream.pipe(res);
    }
    else{
        res.writeHead(404, {"Content-Type": "text/plain"});
        res.end("404 Not Found");
    }

}).listen(3000, () => console.log('Server work'));

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
black1277, 2022-02-21
@black1277

You need to use the http.createServer function See
more about it here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question