RONE
RONE

Reputation: 5485

How to return array from module in NodeJS

I'm writing a program that should filter and print the files of the given directory from the command line based on the file type.

mymodule.js :

var fs = require('fs');
var result=[];
exports.name = function() {
fs.readdir(process.argv[2], function (err, list) { 

    for(var file in list){

        if(list[file].indexOf('.'+process.argv[3]) !== -1){
            result.push(list[file]);
        }
    }


});
};

And in my actual file index.js:

var mymodule = require('./mymodule')
console.log(mymodule.name());

When the run the command

 > node index.js SmashingNodeJS js //In SmashingNodeJS folder print all the .js files

The console.log is printing undefined, please let me know what I am doing wrong here and how to return/bind the content to exports.

Upvotes: 1

Views: 1599

Answers (1)

RONE
RONE

Reputation: 5485

I fixed it by following Bergi's comment above.

mymodule.js :

var fs = require('fs');
exports.name = function(print) { // Added print callback here as param
    var result = [];
    fs.readdir(process.argv[2], function (err, list) { 
        for (var file=0; file<list.length; file++) {
             if (list[file].indexOf('.'+process.argv[3]) !== -1) {
                 result.push(list[file]);
            }
        }
        print(result); // Calling back instead of return 
    });
};

And in index.js file:

var mymodule = require('./mymodule')
mymodule.name(console.log); // pass the console.log function as callback

Upvotes: 2

Related Questions