0

I'm using Filewalker to traverse through a directory. However, for each file, I'd like to perform an asynchronous operation. How do I ensure that done is fired only after all the operations are complete?

filewalker('.')
  .on('file', function(p, s) {
    processAsync(p);
  })
  .on('done', function() {
    console.log('All files have been processed');
  })
.walk();
Shrihari
  • 105
  • 2
  • 10

1 Answers1

1

As on file event doesn't provide any callback param, create files array and add each file to it. Then on filewalker done event use async module to process each file asynchronously.

var filewalker = require('filewalker');
var async = require('async')

function fileAsyncFunc (file, cb) {
  setTimeout(function () {
    console.log('file processed asynchronously')
    cb()
  }, 100)
}

function doneProcessingFiles (err) {
  if (err) {
    return console.error(err)
  }
  console.log('done processing files asynchronously')
}

const files = []
filewalker('./node_modules/filewalker')
  .on('file', function(p, s) {
    //  add file to files array
    files.push({p,s})
  })
  .on('done', function() {
    //  call async functions to each file
    async.each(files, fileAsyncFunc, doneProcessingFiles)
  })
.walk();
Vedran Jukic
  • 841
  • 8
  • 14
  • Yes, this is what I'm currently doing. I was wondering if there was another way to do it. Thank you for your answer :) – Shrihari Apr 15 '17 at 18:55