Node isDirectory() not working properly or i am missing somenthing

I want to get all names of files and directories from path and recognize them as files and directories. but When i run my code sometimes it works and somentimes it shows that directories are files. Here is the code

socket.on('data',function(path){
  fs.readdir('path',function(err, data) {
    var filestatus=[];
    var z=0;
    var i=data.length-1;

    data.forEach(function(file){ 
      fs.stat(file, function(err, stats) {  
        filestatus[z]=stats.isDirectory()
        if (z==i){
          socket.emit('backinfo',{names:data,status:filestatus});
        }
        z++;
      })
    })
  })  
})

During tests i realized that when i slow down data.forEach loop (using console.log(something) it works better(less miss). And this is strange.

This is about 96% incorrect, thank you to JohnnyHK for pointing out my mistake, see the comments below for the real problem / solution.

Because the fs.stat() function call is asynchronous, the operations on the filestatus array are overlapping. You should either use the async library as elmigranto suggested, or switch to using fs.statSync.

More details on what's happening:

When you call fs.stat(), it basically runs in the background and then immediately goes onto the next line of code. When it has got the details of the file, it then calls the callback function, which in your code is the function where you add the information to the filestatus array.

Because fs.stat() doesn't wait before returning, your program is going through the data array very quickly, and mutliple callbacks are being run simultanously and causing issues because the z variable isn't being incremented straight away, so

filestatus[z]=stats.isDirectory()

could be executed multiple times by different callbacks before z gets incremented.

Hope that makes sense!