I'm trying to async filter a list of file paths to return only existing files. I'm using the async library's filterLimit along with fs-extra. Function below:
const asyncFilter = require('async').filterLimit;
const fsExtra = require('fs-extra');
async function filterFiles(fileList){
const existing = await asyncFilter(fileList, 5, (file, callback) => {
console.log(file); // looks good
fsExtra.pathExists(file, (err, exists) => {
const result = err ? false : exists;
console.log(result); // looks good (boolean)
callback(null, result);
});
});
console.log(existing); // always undefined...
}
EDIT 2: Both suggestions below do not work... here is a working version where the deprecated
fs.exists()was replaced withfs.access()Can't you simply do:
NOT WORKING
no need for
fs-extra. I think your issue is thatasync.filterLimit()does not return anything but executes a callback function, so just by assigningasync.filterLimit()to a variable does not mean you get the result in there, you'll getundefinedbecause the function does not return anything!EDIT: Adapted snippet from above based on @Jaromanda X's comment: