admin管理员组文章数量:1295255
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?
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?
Share Improve this question asked Nov 16, 2016 at 10:04 Miha ŠušteršičMiha Šušteršič 10.1k27 gold badges97 silver badges175 bronze badges 1-
its because readdir is async - try using
fs.readdirSync
– naortor Commented Nov 16, 2016 at 10:08
2 Answers
Reset to default 7fs.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)
})
I had the same problem and I solved it by using fs.readdirSync
function getDirectories(path) {
fs.readdirSync(path, function(err, content) {
if (err) {
return err;
} else {
return content;
}
});
}
Should work
本文标签: javascriptfsreaddir returns undefined when called inside a functionStack Overflow
版权声明:本文标题:javascript - fs.readdir returns undefined when called inside a function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741606459a2388005.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论