Question

I have a file path list file_paths, and I want to detect which file exists. If any file exists, I want to read that one. Otherwise call another function, not_found for example.

I wish to use async.detect but I found no way to add a 'Not Found' callback when all the iterators return false.

I've tried this one, but no work. Returned undefined and nothing outputted.

async = require 'async'

async.detect [1,2,3], (item, callback) ->
  callback true if item == 4
, (result) ->
  console.log result ? result : 'Not Found'

If there's another way to do it, please add it to the answer.

Was it helpful?

Solution

from the documentation you mentioned.

in case of detect(arr, iterator, callback)

callback(result) - A callback which is called as soon as any iterator returns true, or after all the iterator functions have finished. Result will be the first item in the array that passes the truth test (iterator) or the value undefined if none passed.

from your question you want to find a way to detect if no file in list is found, which could be done by comparing the result with undefined and checking whether this condition is true.

like

async.detect(['file1','file2','file3'], fs.exists, function(result){

     if(typeof(result)=="undefined") {
         //none of the files where found so undefined
     }

});

OTHER TIPS

I would use async.each and use fs.exists to detect if the file exists. If it exists, then read the file otherwise, call the not found function then proceed to the next item. See sample code I have written on top of my head below.

async.each(file_paths, processItem, function(err) {
  if(err) {
    console.log(err);
    throw err;
    return;
  }

  console.log('done reading file paths..');

});

function notFound(file_path) {
  console.log(file_path + ' not found..');
}

function processItem(file_path, next) {
  fs.exists(file_path, function(exists) {
    if(exists) {
      //file exists
      //do some processing
      //call next when done
      fs.readFile(file_path, function (err, data) {
        if (err) throw err;

        //do what you want here

        //then call next
        next();
      });

    }
    else {
      //file does not exist
      notFound(file_path);
      //proceed to next item
      next();
    }
  });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top