40

I have this code (which works perfectly well) which I've borrowed from an online resource:

var express = require('express');
var bodyParser = require('body-parser');
var logger = require('morgan');

var app = express();

require('./init/db');
require('./init/cache'); //Bring in Redis

//Define Routes
var userRoutes = require('./routes/user');

module.exports = app;

The bit I don't understand is "require" when used in this way? Here is the file it brings in:

//db.js
var mongoose = require('mongoose');
var dbURI = <theURI>;

mongoose.connect(dbURI);

// CONNECTION EVENTS
mongoose.connection.on('connected', function() {
  console.log('Mongoose connected successfully');
});

It's the same with my Redis connection:

//cache.js
var redis  = require("redis");

var redisClient  = redis.createClient(process.env.CACHE_PORT, process.env.CACHE_URL);
redisClient.auth(process.env.CACHE_PASS);

redisClient.on("ready", function () {
  console.log("Cache is connected");
});

but as you can see there is no module.exports anywhere in the db.js or cache.js files! When I google this to understand how it works the examples always talk about module.exports and require together.

Questions

  1. Could someone explain how require works when used on its own like this?

  2. How can I make the cache/Redis connection available so that it can be used in my userRoutes file using something like: var userRoutes = require('./routes/user')(redis);

3
  • You can definitely export mongoose connection to use in other modules as a reference to DB. Just Google it(eg: export mongoose connection) and you will find plenty of examples. Jul 3, 2016 at 17:14
  • My code is working fine and I can query the database from my routes file but I don't understand how!
    – tommyd456
    Jul 3, 2016 at 17:21
  • Excellent question! Thank you for asking. It helped me understand a lot of things and get my work done!
    – kirtan403
    Nov 19, 2016 at 4:49

3 Answers 3

68

Could someone explain what is happening with this code? In other words, how does require work when not used with export.

We almost always see require() being used with module.exports, but you don't have to. When you don't export anything, the code in the imported module will still run, but you can't bind the import to a variable and interact with it.

Consider the following Foo.js module :

var foo = {};

foo.greet = function(){
    console.log('Hello from Foo!');
}

foo.greet();

I can import this module in my main file, like so :

require('./foo');

If I run this main file, the code inside the Foo.js module will run, and Hello from Foo! will be printed to the console.

However, I can't interact with the foo object directly. The following code will not work :

require('./foo');
foo.greet(); //ReferenceError, foo is not defined

I can bind the module import to a variable, but even this will not work :

var foo = require('./foo');
foo.greet(); //TypeError, foo.greet is not a function

To get it to work, I need to export the foo object from my module, using the module.exports that you are familiar with.

This demonstrates that you don't need to export anything from your modules, just like you don't need to bind the imported module to a variable when you are requiring it. The difference is that you won't be able to interact with the code in the imported module, if you don't export what you don't want to make visible in that module.

In the code in your question, importing Redis works because that module is self-contained, you don't need to interact with it in your code. You only need to import the code so that it can run (require the main Redis module and create the client)

5
  • Thanks, this is really helpful. Regarding the Redis part, I need to make the redisClient available in my userRoutes file. Is it a simple case of adding module.exports = redisClient at the bottom of the cache.js file?
    – tommyd456
    Jul 3, 2016 at 17:40
  • Yes, if you export redisClient and bind the require to a variable then you will be able to access it via that variable
    – Drown
    Jul 3, 2016 at 17:42
  • 4
    This is such a great answer! I was searching for something like this from a day after I got my 2 apps working from a single file. Great stuff! And superb question too!
    – kirtan403
    Nov 19, 2016 at 4:49
  • So if I need an exports, I need to edit the module? Is this correct? Oct 13, 2017 at 19:00
  • 1
    The variable inside that code can actually be accessed from outside if you don't 'use strict' and declare it globally. But of course I agree that is a terrible practice.
    – user6269864
    Aug 1, 2018 at 7:19
17

Besides requiring a module that doesn't include exports to run it's side effects it's also possible for a module to define variables in the global scope which can be accessed in the file where the module is required. This happens by defining variables without the var keyword. It's not a good or common practice, but you might encounter it somewhere so it's good to know what is going on.

Example:

// foo.js
bar = 5;

And

// test.js
require('./foo');

console.log(bar);
// prints 5

If barwas defined as:

var bar = 5;

it would be in the module scope and not be accessible in test.js.

1
  • 1
    this is exactly what I was looking for, I wanted to know what happens to variable defined as var when included from a module without export, they get automatically scoped and as such there is no problem with var assignments overrides. thank you! Oct 2, 2018 at 11:50
4

When you call require the module is loaded and executed. So you have a connected mongoose. Actually require makes a function that your entire module code injected there and finally run.

Now, if you want to reuse variables created in modules you should export that. Like :

//cache.js
var redis  = require("redis");

var redisClient  = redis.createClient(process.env.CACHE_PORT, process.env.CACHE_URL);
redisClient.auth(process.env.CACHE_PASS);

redisClient.on("ready", function () {
  console.log("Cache is connected");
});

module.exports = redisClient;
1
  • Thanks, I just added a comment for the other answer that is the same as this. Cheers anyway.
    – tommyd456
    Jul 3, 2016 at 17:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.