Himmators
Himmators

Reputation: 15006

Can I add methods to modules?

I have a funciton inside a node-module:

//app.js
var minify = require("./minify.js")(app, express);

//minify.js
module.exports = function (app, express) {

    ...

    function fileList(dir) {
        return fs.readdirSync(dir).reduce(function(list, file) {
            var name = path.join(dir, file);
            var isDir = fs.statSync(name).isDirectory();
            var isJs = name.endsWith('.js');
            return list.concat(isDir ? fileList(name) : isJs ? [name] : [] );
        }, []);
    }
   ...
};

I want to change it to a method to make my code more readable.

I tried the following, without success:

module.fileList = function(dir) {
    return fs.readdirSync(dir).reduce(function(list, file) {
        var name = path.join(dir, file);
        var isDir = fs.statSync(name).isDirectory();
        var isJs = name.endsWith('.js');
        return list.concat(isDir ? fileList(name) : isJs ? [name] : [] );
    }, []);

module.prototype.fileList = function(dir) {
    return fs.readdirSync(dir).reduce(function(list, file) {
        var name = path.join(dir, file);
        var isDir = fs.statSync(name).isDirectory();
        var isJs = name.endsWith('.js');
        return list.concat(isDir ? fileList(name) : isJs ? [name] : [] );
    }, []);
}

I expect to be able to call the method usint this.fileList or minify.filelist, depending on my scope.

Upvotes: 0

Views: 48

Answers (2)

Nicolas Leucci
Nicolas Leucci

Reputation: 3339

I think this way is easier :

minify.js

module.exports = {

    fileList: function(app, express) {
        // your code here
    },

    Method2: function() {
        // another code here
    }

}

And you can use it like this:

app.js

var minify = require('minify');

minify.fileList(app, express);
minify.Method2();

Upvotes: 0

madox2
madox2

Reputation: 51841

You can return object from exported function:

//minify.js
function fileList(dir) {
    // ...
}

module.exports = function(app, express) {
    //...
    return {
        fileList: fileList
    };
}

//app.js
var minify = require("./minify.js")(app, express);
minify.fileList();

Upvotes: 1

Related Questions