4

Say I have the following module makeDir which checks for the existence of a directory and creates one if it does not exist or simply calls its callback with null if the directory already exists.

Which would be the proper way to export this module?

module.exports = makeDir or module.exports.makeDir = makeDir ?

'use strict';

var fs = require('fs');
var mkdirp = require('mkdirp');

var makeDir = {};

makeDir.handler = function (dstPath, sizesObj, callback) {

    var _path = dstPath + sizesObj.name + "/";

    fs.lstat(_path, function (err, stats) {
        if (err) {
            mkdirp(_path, function (err, made) {
                if (err) {
                    console.log("Error creating directory: %s", err);
                    callback (err, null);
                } else {
                    console.log("Created new directory");
                    callback(null, made);
                }
            });
        } else {
            callback(null);
        }
    });
};

module.exports = makeDir;
hyprstack
  • 4,043
  • 6
  • 46
  • 89

2 Answers2

2

Both methods of using module.exports or module.exports.FUNCTION_NAME are okay but the difference comes when you require these functions.

Let me show the difference using an Example.

a. Assigning function directly to module.exports

// mkdir.js
module.exports = function(){
       console.log("make directory function");
};

// app.js
var mkdir = require("mkdir.js");
mkdir(); // prints make directory function

b. Exporting function at property in module.exports

// mkdir.js
module.exports.first = function(){
                     console.log('make directory function');
};

// app.js
var mkdir = require('mkdir.js');
mkdir.mkdir(); // make directory function

Hope it helps!

KlwntSingh
  • 1,084
  • 8
  • 26
1

module.exports = makeDir;

is the correct method if you are exporting only one object from javascript file.

IN CASE YOU NEED TO EXPORT MORE THAN ONE OBJECTS

var makeDir = {
 obj1 : function(){},
 obj2 : function(){}
}
module.exports = makeDir;

This way you can use makeDir.obj1 and makeDir.obj2 in other file.

MegaMind
  • 653
  • 6
  • 31