Use Express Server to Deliver HTML Files quickly

Create a folder ex. "MyProject"

Use command npm init for initiating package.json

Once setup, install Express module using npm i express --save

Open the folder using VS Code or any other IDE, create a file called server.js ( You may use any name )

Copy paste this below code :


const express = require('express');
const app = express();
const path = require('path');
const port = process.env.PORT || 3000;
app.get('/', function(req, res) {    
      res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(port,()=>{    
      console.log(`started on port ${port}`);
});

You may create multiple route as per your need, use command 


node server.js to start the server



For quick access go to package.json file, and add an entry to scripts category like below example :

Use ctrl + c to stop the server.


{  
   "name": "image",  
   "version": "1.0.0",  
   "description": "",  
   "main": "index.js",  
   "scripts": {    
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node app/server.js"
   },  
   "author": "",
   "license": "ISC",  
   "dependencies": {    
        "express": "^4.17.1"  
   }
}

Quick tip : Every time you change something in node file you need to stop and start the server for getting the updated result. So you may use nodemon package for auto restart, this will save lot of your development time in long run.



Thanks for your time




Comments

Popular posts from this blog

Best coding practice and structure for redux saga with react hooks | Separate watcher and worker saga | React clean code

How to use redux with React Hooks - Creating TodoList

Setting up Redux Devtools for React applications