How to use Global functions in Express JS?
Last Updated :
16 Dec, 2023
In this article, we will learn the global function of Express. Express JS is a web application framework for Node JS. This framework runs on the server-side framework. It is a trendy Express JS framework for building scalable web applications.
There are many functions available in Express JS that are global:
What is the Global function in Express JS?
In Express JS, Global functions are those functions that are globally available or accessible throughout your entire Express application. There are many functions available in Express JS that are globals.
express():
This is the instance of Express JS Function that includes express in the application. It is the entry point in Node JS. It can be used to define middleware functions in our application.
const express = require('express');
const app = express();
Middleware functions:
The middleware() is a core concept of node js. These functions can access the ‘req’ and ‘res’ response object. They can modify these object before reaching the route handler. The following program demonstrates the Middleware function.
Example: Below is the code example of the middleware and express function.
Javascript
const express = require( 'express' );
const app = express();
const logger = (req, res, next) => {
res.send( "Geeks for Geeks" );
next();
};
app.use(logger);
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
|
Output:
Define Custom Global function:
We can also define global function in Expres JS web application framework. Create a module for containing your global function in that file . After import that file in your application
Example: Below is the code example of the global function.
Javascript
const express = require( 'express' );
const app = express();
const globals = require( './globals' );
app.get( '/' , (req, res) => {
res.send(globals.myGlobalFunction());
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
|
Javascript
module.exports = {
myGlobalFunction: () => {
return 'Hello from global function!' ;
},
myGlobalVariable: 'Hello from global variable!' ,
};
|
Output:
Share your thoughts in the comments
Please Login to comment...