Miha Šušteršič Miha Šušteršič - 22 days ago 6
Node.js Question

fs.readdir returns undefined when called inside a function

I am trying to write a function that takes a path and returns all the files inside that directory.

When I do this:

function getDirectories(path) {
fs.readdir(path, function(err, content) {
if (err) {
return err;
} else {
return content;
}
});
}

console.log(getDirectories('./XML/'));


I get
undefined
in the console.

But when I do this:

function getDirectories(path) {
fs.readdir(path, function(err, content) {
if (err) {
return err;
} else {
console.log(content);
}
});
}


I get the expected array with file names as strings.

What am I doing wrong?

Answer

fs.readdir is async use this :

function getDirectories(path, callback) {
    fs.readdir(path, function (err, content) {
        if (err) return callback(err)
        callback(null, content)
    })
}

getDirectories('./XML', function (err, content) {
    console.log(content)
})