What is express.js and installing it in Node.js?

Node.jsServer Side ProgrammingProgramming

Why requires express.js?

Writing core node.js code to fetch request data and parsing it is complex enough. As we saw in previous posts, we wrote data and end event to get the simple request data.

Express makes the process simpler. It helps developers to focus more on writing business logic instead of node’s internal complexity.

Express.js does the heavy lifting of node’s internal workings. There are some other alternatives to express.js are also available e.g. Adonis.js, Sails.js etc.

Installing express.js

Why –save and not –save-dev for express?

Express is a major runtime required library so it’s a dependency and not just dev dependency . That’s why we install it without –save-dev

Once added, we can see it in package.json file −

{
   "name": "dev",
   "version": "1.0.0",
   "description": "",
   "main": "App.js",
   "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "nodemon App.js"
   },
   "author": "",
   "license": "ISC",
   "devDependencies": {
      "nodemon": "^2.0.3"
   },
   "dependencies": {
      "express": "^4.17.1"
   }
}

Import express in app.js

const express = require('express');

starting express.js −

const app = express();

So express is a function. It starts its internal process with the execution of express()

We can use express const in http createServer directly −

const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
server.listen(3000);

Now, we can run app, but it won’t handle any request as we have not defined any routes for it. In the next articles we will see the middleware concepts of express.js

raja
Published on 13-May-2020 16:08:06
Advertisements