Reputation: 81
My question is: Why do we use only the variable name 'app' to store the return of the function express and why not other variables? Express is a module in node, how can it be a function? Please help me as I am new to node.js! The following code is an example of a very basic route.
var express = require('express')
var app = express()
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
res.send('hello world')
}
Upvotes: 0
Views: 1428
Reputation: 707148
To use the express
library, you create an instance of the express library. You do that by calling express()
and it returns an object which popular convention names app
, but you can name it anything you want.
const express = require('express'); // load express library
const app = express(); // call express factory to create
// an instance of the express library
You can name the variable app
anything you want. The name app
is used by popular convention, but you could just as easily have done:
const express = require('express');
const myApp = express();
myApp.get('/', ...);
Note, one of the reasons express requires you to create an instance is that it is possible to have multiple servers in the same piece of code, each that is their own instance of express (app1, app2, app3, etc...). If it didn't require you to create an instance somehow and was only using module-level state for all state, then you could only ever have one server per node.js process which is more limiting than need be.
Folks who listen on both http and https often have two servers in the same app. Or you may serve web pages on one port and serve an API on another port. So the designers of the Express library designed it so that you need an INSTANCE of the express object before you can call .get()
on it (thus allowing one to have multiple and completely separate instances) and the express library has offered a factory function express()
you can call to create that instance.
Upvotes: 2
Reputation: 92430
The variable name you choose is arbitrary. app
is chosen by convention.
In node you can export a function from a module. For example:
test_mod.js:
function test() {
console.log("Testing")
}
module.exports = test
test.js:
var t = require('./test_mod')
t()
Upvotes: 1
Reputation: 358
You can all it anything instead of an app, we call this app because in node.js application we create different apps for different purposes. Please see this for more details, this is very helpful : https://stackoverflow.com/a/27599657/9211830
Also I will suggest that you should watch some tutorials of Node.js and Express.
Upvotes: 1
Reputation: 136
App is define as variable types as object or instance of express class,We are able to use another variable name of it as, route = express()
Upvotes: 0