2

I'm trying to make a simple NodeJS module with the following pattern:module.exports = function () {}. My problem is that when I write exports.myFunc = myFunc; it works well, but when I write module.exports = myFunc; it doesn't work.

Here's some of my code snippets:

function.js:

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

var i = 0;

function getFilesByExtArgs (dir, ext){
    fs.readdir(dir, function (err, data){
                while (i <= data.length){
                    if (path.extname(data[i]) == ('.' + ext))
                        console.log(data[i]);
                    i++;
                }
        });
}

exports.getFilesByExtArgs = getFilesByExtArgs;

module.js:

var myModule = require('./listFilesByExtArgs');

myModule.getFilesByExtArgs(process.argv[2], process.argv[3]);

How can I make my code work with the pattern needed ?

Mehdi
  • 329
  • 2
  • 6
  • 16

2 Answers2

3

This is because of different behaviors of module.exports and exports.property. So when your write module.exports = myFunc; you actiually make a full module as a func. It uses following way:

var myModule = require('./listFilesByExtArgs');
// In mymodule is actually alias to a func listFilesByExtArgs
myModule(process.argv[2], process.argv[3]);

A full answer you can found here.

Community
  • 1
  • 1
vanadium23
  • 3,516
  • 15
  • 27
1
module.exports = myFunc

exports the myFunc function as the module while

exports.myFunc = myFunc

exports the myFunc function as a myFunc property of the exported module.

so you either use

// case: module.exports = myFunc
var myModule = require('myModule');
myModule();

or

// case: exports.myFunc = myFunc
var myModule = require('myModule');
myModule.myFunc();
Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77