Mehdi
Mehdi

Reputation: 337

Create a NodeJS module

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 ?

Upvotes: 2

Views: 220

Answers (2)

Jerome WAGNER
Jerome WAGNER

Reputation: 22412

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();

Upvotes: 1

vanadium23
vanadium23

Reputation: 3586

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.

Upvotes: 3

Related Questions