I just came to this terrible situation when I have an array of strings, each of which represents a possibly existing file (for example, var files = ['file1', 'file2', 'file3'] . I need to skip these file names and try to find out if it exists in the current directory and if so, stop the loop and forget the rest of the remaining files, so basically I want to find the first existing file of these files and return to the hard-coded message if nothing is found.
This is what I have:
var found = false; files.forEach(function(file) { if (found) return false; fs.readFileSync(path + file, function(err, data) { if (err) return; found = true; continueWithStuff(); }); }); if (found === false) {
This is bad. It blocks (readFileSync), so it slows down.
I cannot just provide callback methods for fs.readFile , it is not so simple because I need to take the first element found ... and callbacks can be called in any random order. I think one way would be to have a callback that increments the counter and stores a list of found / not found information and when it reaches the files.length counter, then checks for the found / not found information and decides what to do next.
This is painful. I see superior performance in the case of I / O, but this is unacceptable. What is my choice?
Tower
source share