Hi, I have the following code:
var fs = require('fs');
function search(text) {
var response = [];
fs.readdir('documents',(err, files) => {
files.forEach(file => {
if(file.toLowerCase().indexOf(text.toLowerCase()) != -1){
console.log("Encontrado " + file);
response.push(file);
}
})
});
return response;
}
exports.search = search;
What it does is search a folder for all the files that contain in their name( file
) a certain substring( text
), the idea is that all the files that match must store their name in the array response
. The problem is that when the array is returned, it gives me appears empty (prints me []
)
As you can see I have a console.log to see if at some point a match is found and I have already confirmed that this happens, now the problem is that it seems that the push line is never executed...
You are doing one of the asynchronous functions, and therefore by the time you get to your
return
, absolutely no line of your filter has been executed , so you return aarray
void.2 options:
1. Use callbacks
2. Use synchronous functions