Open In App

How to use Global functions in Express JS?

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.




const express = require('express');
const app = express();
 
// Middleware function
const logger = (req, res, next) => {
    res.send("Geeks for Geeks");
    next(); // Call the next middleware function in the chain
};
 
// Use the middleware for all routes
app.use(logger);
 
 
// Start the server
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.




const express = require('express');
const app = express();
 
const globals = require('./globals');
 
app.get('/', (req, res) => {
    res.send(globals.myGlobalFunction());
});
 
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});




//Example of the global function
module.exports = {
    myGlobalFunction: () => {
        return 'Hello from global function!';
    },
    myGlobalVariable: 'Hello from global variable!',
};

Output:


Article Tags :