Home > database >  create server in 'node.js' VS 'express.js'
create server in 'node.js' VS 'express.js'

Time:07-27

Hi all, I am new to node.js and express.js

I am having little bit confusion on creating server on node.js and express.js.

In Node.js we use the http module to create a server.

where as in express we don't use any http module, still we are able to create a server. How server is created here ? Is app.get() is creating it ?

I tried to google the difference but couldn't get the right explanation, pls someone help me here or share a link for a document so, I can understand it better.

// creating server using Node.js

var http = require('http');
var fs = require('fs'); 

var htmlData;

fs.readFile('index.html',(err, data)=>{
  if(err) throw err;
    htmlData = data;
});

 
http.createServer(req, res) {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(htmlData); //read the file & write the data content
      res.end();
  }).listen(8000,()=>{console.log("PORT is 8000")}); 




// creating server using Express.js

const express = require('express');
const fs =require('fs');
const app = express();

let htmlData;

fs.readFile('index.html','utf-8',(err,data)=>{
    htmlData = data;
})

app.get('/',(req,resp)=>{
    resp.writeHead(200,{'content-type':'text/html'}).write(htmlData).end();
}).listen(8000);

CodePudding user response:

express.js is built on top of Node.js and uses Node's networking and web framework behind the scenes.

express.js is structured to use "middlewares" which are modules of functionality (basically functions) that process some input and changes state/adds functionality.

For examples there are middlewares specifically to handle http requests received by Node.js before they are passed to your application.

See https://expressjs.com/en/resources/middleware.html and http://expressjs.com/en/resources/middleware/body-parser.html

CodePudding user response:

Express is just a library for node js. It uses http module of node to create a server. You call app.use, but this function does a lot of stuff, including http.createServer. Apart from server, express uses middlewares, extending another library called connect. If any method of express is not explained in express documentation, read docs for connect.

If you are learning node now use http, because express provides too much features and does a lot of work instead of you, not allowing to fully understand what is happening

CodePudding user response:

app.listen create the server on express. In express we don't have to use app.createServer(). we can directly use app.listen(3000). Express make our life easier.

  • Related