Tuesday, 6 June 2017

What does require('express')() do in NodeJS

As far as I understand, require('express')() doesn't create a server, it just bundles the functions together. But if so, how does the following code run without server?

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

app.get('/', function (req, res) {
  res.send('Hello World!')
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

Also, if it does create a server, why do I need to import http module and manually create a server in the following example?

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

I am very confused. Thanks in advance.



via SKG

No comments:

Post a Comment