Async operation on each file with npm filewalker

226 Views Asked by At

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

There are 1 best solutions below

1
On

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