Search code examples
javascriptnode.jsfilewalker

Exit stream manually before `on('exit')` event is reached while using filewalker


I am using filewalker npm package to walk through files.

I am trying to limit amount of files that would be read in stream by exiting stream once a specific condition is met. (e.g. streamed 5 file paths) rather than waiting exit event. (This is due to huge amount of files and I want to paginate stream)

  getFilePath: (dirPath, fileMatchExpression) => {
    return new Promise((resolve, reject) => {
      filewalker(dirPath)
      .on('file', filePath => {
        if (filePath.match(fileMatchExpression)){
          resolve(filePath)
          // how to force exit on this line?
        }
      })
      .on('error', err => reject(err))
      .on('done', _ => console.log('DONE!!'))
      .walk()
    })

Is there a way to cancel/exit stream by manually?


Solution

  • While this is not answer to the question, I solved this issue by replacing filewalker library with walk. It basically does the same thing, except it has next function which allows me to control if program will execute next or not.

    const walk = require('walk')
    let walker = walk.walk(dataDirPath, {followingLinks: false})
    let counter = 0
    walker.on('file', (root, stat, next) => {
      console.log(root + '/' + stat.name);
      counter++
      if(counter < 1) next()
    })