-1

How it is work? function(){...}(); I can't understand what's going on. I think this is javascript not node.js puzzle. But I can not find solution.

fs.readdir(filesDir, function(err, files) {
if (err) throw err;
for (var index in files) {
    **var task = (function(file) {**
        return function() {
            fs.readFile(file, function(err, text) {
                if (err) throw err;
                countWordsInText(text);
                checkIfComplete();
            });
        }
    **})(filesDir + '/' + files[index]);**
    tasks.push(task);
}
for (var task in tasks) {
    tasks[task]();
Krish R
  • 22,583
  • 7
  • 50
  • 59
  • 4
    It defines and immediately calls the function. The brackets around it enable this by converting the line into a statement (instead of a declaration). This has been asked before, but I can't find a direct link right now. – Dave Nov 10 '13 at 10:11
  • If you're interested, the reason for this code is to keep file local to the current iteration. Without it, file would be scoped too broadly, and all the callbacks would see the last file, instead of their own. – Dave Nov 10 '13 at 10:14

1 Answers1

1

This code is a inline execution of a js function. Every js-function can be defined and executed inline:

var result = (function(params) { /* some functionality */ })(params);

in your case:

 var task = (function(file) {
            return function() {
                fs.readFile(file, function(err, text) {
                    if (err) throw err;
                    countWordsInText(text);
                    checkIfComplete();
                });
            }
        })(filesDir + '/' + files[index]);

can also be written like:

// define the funktion 
var task = function(file) {
                return function() {
                    fs.readFile(file, function(err, text) {
                        if (err) throw err;
                        countWordsInText(text);
                        checkIfComplete();
                    });
                }
            };

// execute the function with parameter
var result = task(filesDir + '/' + files[index]);
Martin
  • 3,096
  • 1
  • 26
  • 46