Mohit Bhardwaj
Mohit Bhardwaj

Reputation: 10083

Should 'require()' be used locally or globally in NodeJS (ExpressJS)?

I have a confusion regarding importing packages in ExpressJS using require(). I was including some packages e.g. nodemailer, bcryptjs locally, i.e. calling require on them inside functions. So, I had to require them multiple times in a single route file.

A colleague suggested that all require statements should come only once, either at the top of that route file or in app.js file. I'm slightly confused. Can someone please suggest the best way to require packages inside middlwares.

Example Code: Suppose e.g. I need to send an email in a middleware function. I have the code for this as given below:

var nodemailer = require("nodemailer");
                var mailTransport = nodemailer.createTransport();
                var mailOptions = {
                    from: constants.mail_sender_email,
                    to: constants.user_won_recipient_mails,
                    subject: templateContext.subject,
                    text: subject + ".\n",
                    html: results.html
                };

Everytime I need to send an email, I use require('nodemailer') statement again. Should I instead require it once in that route file i.e. index.js or perhaps in app.js? But then there are cases like require('ObjectID'), which are not used very frequently. Would it be good to globally required such packages also?

Thanks.

Upvotes: 0

Views: 82

Answers (2)

Vishal
Vishal

Reputation: 537

require('requiredFile / requiredModule'); returns you the context of the file and expose the exported module from requiredFile or requiredModule.

If you want to use the module at global level require and call it inside app.use(), so that you can use it each time a request is processed.

But if you want to use it locally on for a particular file then require it on the top of the file and cache it in a variable, then use that variable throughout the file (similar to what you have written in your sample code)

Upvotes: 1

Anton Stafeyev
Anton Stafeyev

Reputation: 2859

Well here is an example.

http.createServer(yourCallback(req, res)
{
    if(req.Host == "a")
    {
        require("moduleA")(req, res);
    }else
    {
        require("moduleB")(req, res);
    }
}).listen(80);

In this case server will choose which module to use. for example you have multiple hosts, and you create that hosts via js module. so u dont need to import all your host files in to an app. after it is done garbage collector takes it away.

in case u know you are going to be using module a lot. then u just declare it as global module. like fs, http, etc.

Upvotes: 0

Related Questions