1

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.

4
  • Your name() method doesn't return anything, so what do you expect? Commented Mar 30, 2015 at 11:46
  • 2
    Of course it cannot return the array, as it does asynchronously read a file. Use a callback instead (to be used as mymodule.name(console.log)). Commented Mar 30, 2015 at 11:47
  • Thanks friend, I fixed it, from your suggestion. Commented Mar 30, 2015 at 11:52
  • Yes I did the exact same thing below Commented Mar 30, 2015 at 11:56

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.