Konstantin Viikset Konstantin Viikset - 5 months ago 19
Node.js Question

Nodejs file exist

If i try check exist just one file (whom actualy exists), my test passing
successfully. But if i try add in asserts non-existing file, both test passed with error

describe('script entry points', function () {
entryJs = {
"app": "./coffee/app",
"shame": "./coffee/shame"
};

for(var pointJs in entryJs) {
pathJs = 'web/js'+pointJs+'.js';
it('should return true when '+pathJs+' file exist', function () {
fs.stat(pathJs, function(err, data) {
if (err)
console.log('it does not exist');
else
console.log('it exists');
});
});
}
});

Answer

Add console.log(pathJs); just before fs.stat and you'll find out that fs.stat is called twice with same pathJs value.

By the time the fs.stat gets called first time the pathJs variable holds the value assigned to it in last for loop cycle.

The reason is asynchronous nature of node.js. You need to use closure.

Solution:

for(var pointJs in entryJs) { 
    pathJs = 'web/js/'+entryJs[pointJs]+'.js';     

    (function(path){
         it('should return true when '+path+' file exist', function () { 

              fs.stat(path, function(err, data) { 
                   if (err) 
                       console.log('it does not exist');           
                   else 
                        console.log('it exists'); 
               }); 
         });
    })(pathJs);
}