Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of exporting module [duplicate]

Tags:

node.js

module

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;
like image 243
hyprstack Avatar asked Oct 21 '25 10:10

hyprstack


2 Answers

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!

like image 128
KlwntSingh Avatar answered Oct 24 '25 19:10

KlwntSingh


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.

like image 20
MegaMind Avatar answered Oct 24 '25 18:10

MegaMind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!