Node itself can serve static files without express or any other module..?

It's ridiculous to attempt to create a node application without npm dependencies, because the base of nodejs is just that -- a base. Unless you feel like implementing entire protocols, you're better off using a minimal, well maintained npm module that does that for you. That said, here is the very basic thing you asked for (without MiME, eTags, caching, etc, etc):

var basePath = __dirname;
var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function(req, res) {
    var stream = fs.createReadStream(path.join(basePath, req.url));
    stream.on('error', function() {
        res.writeHead(404);
        res.end();
    });
    stream.pipe(res);
}).listen(9999);

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

function send404(response){
  response.writeHead(404, {'Content-Type': 'text/plain'});
  response.write('Error 404: Resource not found.');
  response.end();
}

const mimeLookup = {
  '.js': 'application/javascript',
  '.html': 'text/html'
};

const server = http.createServer((req, res) => {
  if(req.method == 'GET'){

    let fileurl;
    if(req.url == '/'){
      fileurl = 'index.html';
    }else{
      fileurl = req.url;
    }
    let filepath = path.resolve('./' + fileurl);

    let fileExt = path.extname(filepath);
    let mimeType = mimeLookup[fileExt];

    if(!mimeType) {
      send404(res);
      return;
    }

    fs.exists(filepath, (exists) => {
      if(!exists){
        send404(res);
        return;
      }

      res.writeHead(200, {'Content-Type': mimeType});
      fs.createReadStream(filepath).pipe(res);

    });

  }
}).listen(3000);
console.log("Server running at port 3000");

its very simple, node already provide fs module from which u can read that html file and append on response obj like this:

response.writeHead(200, {"Content-Type": "text/plain"});
//here is the code required
fs.readFile("./xyz/index.html", (err,fileContent) =>
{
  response.end(fileContent);
});

but the problem here is you will only get the HTML document not the resources inside that HTML files which are stored in different folders like if you have this code in your index.html

<link rel="stylesheet" href="../css/index.css" />

this index.css will not be allowed by the node server. But i guess your question is solved.

Tags:

Node.Js