showing results for - "serving html and css with node js"
Maite
28 Oct 2017
1// HTTP Module for Creating Server and Serving Static Files Using Node.js
2// Static Files: HTML, CSS, JS, Images
3// Get Complete Source Code from Pabbly.com
4
5var http = require('http');
6var fs = require('fs');
7var path = require('path');
8
9http.createServer(function(req, res){
10
11    if(req.url === "/"){
12        fs.readFile("./public/index.html", "UTF-8", function(err, html){
13            res.writeHead(200, {"Content-Type": "text/html"});
14            res.end(html);
15        });
16    }else if(req.url.match("\.css$")){
17        var cssPath = path.join(__dirname, 'public', req.url);
18        var fileStream = fs.createReadStream(cssPath, "UTF-8");
19        res.writeHead(200, {"Content-Type": "text/css"});
20        fileStream.pipe(res);
21
22    }else if(req.url.match("\.png$")){
23        var imagePath = path.join(__dirname, 'public', req.url);
24        var fileStream = fs.createReadStream(imagePath);
25        res.writeHead(200, {"Content-Type": "image/png"});
26        fileStream.pipe(res);
27    }else{
28        res.writeHead(404, {"Content-Type": "text/html"});
29        res.end("No Page Found");
30    }
31
32}).listen(3000);Copy