Node - Serving static files from scratch (without using any package)

Node - Serving static files from scratch (without using any package)

·

0 min read

As a fullstack developer or front end developer, we do ship static assets through node packages with express, or webpack-dev-server or anything it can be, but hardly most of us(but at least myself) might not understood, how it being served under the hoods. Recently I gave a try, learned few things and thought of sharing it.

I will be explaining it step by step,

Creating basic http server using http module with few lines

const http = require('http');
const server = http.createServer();

server.on('request', ( req, res ) => {
  res.end('Hello, Serving content from node server');
});

server.listen(6060,() => console.log('Server is running at port 6060'));

Adding list of most commonly used MIME types to the above code.

const http = require('http');

const server = http.createServer();

// Supporting html, css, JS, JSON, images, and font assets  
const mimeTypes = {
  '.html': 'text/html',
  '.js'  : 'text/javascript',
  '.css' : 'text/css',
  '.json': 'application/json',
  '.png' : 'image/png',
  '.jpg' : 'image/jpg',
  '.woff': 'application/font-woff',
  '.ttf' : 'application/font-ttf',
};

server.on('request', ( req, res ) => {
  res.end('Hello, Serving content from node server');
});

server.listen(6060,() => console.log('Server is running at port 6060'));

Serving assets through http requests

Serving default file as index.html on root or for absolute path static requests only else responding with just simple string. We can extend this and support restful APIs, but it's out of scope for this article.

The folder structure looks as,

http-static
  public
    -index.html
    -app.js
  server.js
const http = require('http');
const path = require('path');
const fs = require('fs');

const server = http.createServer();

// Supporting html, css, JS, JSON, images, and font assets  
const mimeTypes = {
  '.html': 'text/html',
  '.js'  : 'text/javascript',
  '.css' : 'text/css',
  '.json': 'application/json',
  '.png' : 'image/png',
  '.jpg' : 'image/jpg',
  '.woff': 'application/font-woff',
  '.ttf' : 'application/font-ttf',
};

server.on('request', (req, res) => {

  const { method, url } = req;

  const fileExtension = path.extname(url);

  // Servering static files 
  if(method === 'GET' && (url === '/' || fileExtension)){

    // Default file index.html and it will be served on root
    let filepath = path.resolve(__dirname, './public/index.html');
      if(path.extname(url)){
        filepath = `${__dirname}${url}`;
      }

    let contentType = mimeTypes[fileExtension] || 'text/plain';

    fs.readFile(filepath, (err, data) => {
      if(data){
        res.writeHead(200,{'Content-Type':contentType });
        res.end(data);
      }else if(err){
        throw err
      }
    });

  }else{
    res.end('Hello Node world');
  }

});
server.listen(6060,() => console.log('Server is running at port 6060'));

Here GitHub code link - https://github.com/YuvarajTana/node-http-static-server

I hope it will help you guys and feedbacks are welcome. Thanks :)

Note: This is to understand under the hoods of how node frameworks serve static files not for production, off course you can improve and use it.