noobcoderiam
noobcoderiam

Reputation: 508

A little confused about var app= express()

I've been reading through the docs but still don't quite understand why we store express() inside an app variable.

I know we can't just call methods using express().get and .post because I tried and failed, but why?

How come it doesn't work like if we would call a function from the module.exports of any file we require?

I'm just really confused lol.

Upvotes: 2

Views: 183

Answers (2)

Charles Landau
Charles Landau

Reputation: 4265

express expects you to create an instance object of it and use that. A short way of answering is to say "because that's what the makers of express expect from their users."

Across your script the expectation from the developers is that your .get and .post methods are called against a common instance of express. In this way, we can say that the call to express() initializes the instance and returns an object, which you store in app.

Edit in response to your comment:

express is a function that creates a new object based off a class

express() initializes the app object and I have not yet encountered a situation where I need to know specifically how. I have no idea if it's a function or a class. This is "encapsulation", the concept in OOP where there is a clear boundary between what you, the user of a module need to know in order to use it, and what the developer of the module needs to know to keep it working.

...dependent on the method used(ex: .get), and then uses that instance to allow us to make a route that returns things such as the req and res parameters in the callback?

The initialized object implements methods, callbacks, et al (like .get as you describe.)

All of which is in the express module?

All of which is the conventional pattern for working with the express API.

Upvotes: 3

MazBeye
MazBeye

Reputation: 912

What really happens when your code call var express = require('express'), it actually imports the Factory Method called createApplication (source code here).

Meanwhile, when you do express().get and express().post, you're expecting that it will return the same instance of express app object, while it's not. Your code will work if express is using Singleton pattern under the hood (resulting in the same instance being returned on every call to express()). While the Factory Method design pattern will always create a new instance.

That said, every route you add directly using express().get or express().post will always be spread across many different application instance. So basically, it will work as advertised, but not as you expected to be.

Upvotes: 2

Related Questions