Home > database >  How to import file globally in node js
How to import file globally in node js

Time:12-31

I have created a helper.js file that will contain helper functions. In order to use the helper functions, I have to import the file in all the locations where I want it to be used. Is there any way I can load/import the helper.js file globally?

helper.js

module.exports = {
    responseObject: function (status, message, data, error) {
        return {
            status: status,
            message: message,
            data: data,
            error: error
        }
    }
}

index.js

// load mongoose
require('./db/mongoose')

const express = require('express')
const app = express()
const port = process.env.PORT || 3000

app.use(helper)

// load routers
const userRouter = require('./routers/user')

app.use(express.json())     // automatically converts incoming requests to json
app.use(userRouter)

app.listen(port)

UserController.js

const User = require("../models/user")
const helper = require("../helper")

exports.createUser = async (req, res) => {
    const user = new User(req.body)

    try {
        await user.save()
        res.status(201).send({
            status: true,
            message: 'Registration success',
            data: user,
            error: {}
        })
    } catch (error) {
        const response = helper.responseObject(false, "Wrong", {}, error)
        res.status(400).send(response);
    }
}

CodePudding user response:

From the documentation:

In browsers, the top-level scope is the global scope. This means that within the browser var something will define a new global variable. In Node.js this is different. The top-level scope is not the global scope; var something inside a Node.js module will be local to that module.

This means you can't just define your responseObject in the "global" scope, as it always refers to the scope local to the module and will not be available to other modules.

But there's a way to do it, although I would not recommend it (search Google or SO why that's the case, this has been discussed in detail already). You can add your function/variable to the global object (which is somewhat similar to the window keyword in browsers):

// in your app.js "add" the exported stuff from the helper-module to the global object
const express = require('express')
...
global.myHelper = require('./helper');


// in e.g. your user-controller you could then access it like
const response = global.myHelper.responseObject(false, "Wrong", {}, error)
  • Related