Home > other >  JavaScript importing module confusion
JavaScript importing module confusion

Time:12-24

When I am importing 'http' module, I use

Var http = require('http');
http.createServer(function(req,res){......
}.listen(8080)

But when I am importing express module, I use

const express = require('express');
const app = express();
app.get('/', (req,res)=>{........
}
app.listen()

Why do I need to create const app = express(); but not const app = http(); in the code?

CodePudding user response:

None of your question really has anything to do with importing.

When you do this:

const app = express();

You are creating an instance of the Express class. The express function is a factory function that creates an object when you call it (in this case it's a function object). It is not an http server. It is a both a parent object for a bunch of methods and the main request handler for routing incoming http requests.

When you then do:

app.listen()

That creates your http server. In fact, the code inside the .listen() method just creates the http server for you and registers app as the request handler for incoming connections.

If you look at the code for app.listen(), you will just see this:

app.listen = function listen() {
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

Which just creates an http server instance with the app function/object as the main request handler and then it calls .listen() to start the server.

So, app.listen() is just a shortcut. You could have used the http module yourself to create your own server object and then registered your app object with it, but app.listen() just does that for you.


As a teaching alternative, there are lots of other ways to arrange the code. You could also do this:

const express = require('express');       // load express module
const app = express();                    // create express instance
const http = require('http');             // load http module
const server = http.createServer(app);    // create http server
                                          // and register express listener
server.listen(80);                        // start http server

This would not take advantage of the shortcut in app.listen(), but would work the same.

CodePudding user response:

express exports a function from the module. http exports an object that has functions.

Every library author chooses their own way to export their library.

Here is an example of how they are implemented.

module.exports = function() {
 // code here
 return {
   // calling the function returns an object
 }
}
module.exports = {
  createServer() {
  }
}
  • Related