Node.js 'Not Found' callback for async.detect?

两盒软妹~` 提交于 2019-12-12 03:10:01

问题


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.


回答1:


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
     }

});



回答2:


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();
    }
  });
}


来源:https://stackoverflow.com/questions/18426378/node-js-not-found-callback-for-async-detect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!