问题描述
我正在尝试在目录中创建特定文件的数组;它将通过一些测试用例来确保它符合给定的标准.
I am trying to create an array of specific files in a directory; which will go through a few test cases to make sure it fits a given criteria.
我正在使用fs.readdir
方法,但是它没有返回promise
,这意味着我不能push
到array
.
I'm using the fs.readdir
method, but it doesn't return a promise
meaning I cannot push
to an array
.
我的想法是用我实际要输出的文件填充一个数组(arr
),然后对该数组进行处理.但是因为readdir
是异步的,并且我不能将.then()
链接到它,所以我的计划被取消了.
My idea was to populate an array (arr
) with the files I actually want to output and then do something with that array. But because readdir
is asynchronous and I can't chain a .then()
onto it, my plans are quashed.
我也尝试过使用readdirSync
进行相同的操作,但无济于事.
I've also tried the same thing with readdirSync
to no avail.
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));
var arr = [];
fs.readdirAsync(folder).then( files => {
files.forEach(file => {
fs.stat(folder + '/' + file, (err, stats) => {
if(!stats.isDirectory()) {
arr.push(file);
return;
}
});
});
})
.then( () => {
console.log(arr);
});
推荐答案
我知道了;我只需要使用statSync
而不是stat
I figured it out; I just needed to use statSync
instead of stat
const fs = require('fs');
var arr = [];
var files = fs.readdirSync(folder);
files.forEach(file => {
let fileStat = fs.statSync(folder + '/' + file).isDirectory();
if(!fileStat) {
arr.push(file);
}
});
console.log(arr);
这篇关于将`fs.readdir`与`.then`链接以返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!