user465001 user465001 - 23 days ago 11
Javascript Question

Why does this nodejs code output in the same order regardless of which function comes first?

In this code, no matter what order I put the functions, the files in the directory are always printed before the name of the directory:

var fs = require('fs');

fs.realpath(__dirname, function(err, path) {
if (err) {
console.log(err);
return;
}
console.log('Path is : ' + path);
});

fs.readdir(__dirname, function(err, files) {
if (err) return;
files.forEach(function(f) {
console.log('File: ' + f);
});
});

File: text_1.txt
File: text_2.txt
File: text_3.txt
Path: /home/user/docs


So, If fs.readdir() was the first function the output would be the same. Why does this happen?

Answer Source

These functions are asynchronous, so the order you put them in the file has little to do with the order in which the operations are performed. The readdir operation is probably much faster, so it is getting completed before the realpath operation.

In order to perform these operations in order, you can put the calls to one inside the callback of the other.

var fs = require('fs');

fs.realpath(__dirname, function(err, path) {
    if (err) {
        console.log(err);
        return;
    }
    console.log('Path is : ' + path);
    fs.readdir(__dirname, function(err, files) {
        if (err) return;
        files.forEach(function(f) {
            console.log('File: ' + f);
        });
    });
});