How does require() in node.js work?


I tried this:

// mod.js
var a = 1;
this.b = 2;
exports.c = 3;

// test.js
var mod = require('./mod.js');
console.log(mod.a);    // undefined
console.log(mod.b);    // 2
console.log(mod.c);    // 3, so this === exports?

So I image that require() may be implement like this:

var require = function (file) {
    var exports = {};
    var run = function (file) {
        // include "file" here and run
    run.apply(exports, [file]);
    return exports;

Is that right? Please help me to understand require(), or where can I find the source code. Thanks!

2/28/2012 2:56:43 AM

Accepted Answer

Source code is here. exports/require are not keywords, but global variables. Your main script is wrapped before start in a function which has all the globals like require, process etc in its context.

Note that while module.js itself is using require(), that's a different require function, and it is defined in the file called "node.js"

Side effect of above: it's perfectly fine to have "return" statement in the middle of your module (not belonging to any function), effectively "commenting out" rest of the code

9/29/2016 1:24:18 AM

Andrey showed the source code, but if you also wonder how to use it, the easy and simple explanation is here (

These were two good examples for me.

//foo.js, multiple methods
var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is ' + circle.area(4));

var PI = Math.PI;
exports.area = function (r) {
  return PI * r * r;
exports.circumference = function (r) {
  return 2 * PI * r;

var square = require('./square.js');
var mySquare = square(2);
console.log('The area of my square is ' + mySquare.area());

//square.js, single method
module.exports = function(width) {
  return {
    area: function() {
      return width * width;

My favourite pattern is

(function (controller) {

  controller.init = function (app) {

    app.get("/", function (req, res) {
        res.render("index", {});


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow