Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4005372
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T08:23:08+00:00 2026-05-20T08:23:08+00:00

I would like to perform some arbitrarily expensive work on an arbitrarily large set

  • 0

I would like to perform some arbitrarily expensive work on an arbitrarily large set of files. I would like to report progress in real-time and then display results after all files have been processed. If there are no files that match my expression, I’d like to to throw an error.

Imagine writing a test framework that loads up all of your test files, executes them (in no particular order), reports on progress in real-time, and then displays aggregate results after all tests have been completed.

Writing this code in a blocking language (like Ruby for example), is extremely straightforward.

As it turns out, I’m having trouble performing this seemingly simple task in node, while also truly taking advantage of asynchronous, event-based IO.

My first design, was to perform each step serially.

  1. Load up all of the files, creating a collection of files to process
  2. Process each file in the collection
  3. Report the results when all files have been processed

This approach does work, but doesn’t seem quite right to me since it causes the more computationally expensive portion of my program to wait for all of the file IO to complete. Isn’t this the kind of waiting that Node was designed to avoid?

My second design, was to process each file as it was asynchronously found on disk. For the sake of argument, let’s imagine a method that looks something like:

eachFileMatching(path, expression, callback) {
  // recursively, asynchronously traverse the file system,
  // calling callback every time a file name matches expression.
}

And a consumer of this method that looks something like this:

eachFileMatching('test/', /_test.js/, function(err, testFile) {
  // read and process the content of testFile
});

While this design feels like a very ‘node’ way of working with IO, it suffers from 2 major problems (at least in my presumably erroneous implementation):

  1. I have no idea when all of the files have been processed, so I don’t know when to assemble and publish results.
  2. Because the file reads are nonblocking, and recursive, I’m struggling with how to know if no files were found.

I’m hoping that I’m simply doing something wrong, and that there is some reasonably simple strategy that other folks use to make the second approach work.

Even though this example uses a test framework, I have a variety of other projects that bump up against this exact same problem, and I imagine anyone writing a reasonably sophisticated application that accesses the file system in node would too.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T08:23:09+00:00Added an answer on May 20, 2026 at 8:23 am

    As it turns out, the smallest working solution that I’ve been able to build is much more complicated than I hoped.

    Following is code that works for me. It can probably be cleaned up or made slightly more readable here and there, and I’m not interested in feedback like that.

    If there is a significantly different way to solve this problem, that is simpler and/or more efficient, I’m very interested in hearing it. It really surprises me that the solution to this seemingly simple requirement would require such a large amount of code, but perhaps that’s why someone invented blocking io?

    The complexity is really in the desire to meet all of the following requirements:

    • Handle files as they are found
    • Know when the search is complete
    • Know if no files are found

    Here’s the code:

    /**
     * Call fileHandler with the file name and file Stat for each file found inside
     * of the provided directory.
     *
     * Call the optionally provided completeHandler with an array of files (mingled
     * with directories) and an array of Stat objects (one for each of the found
     * files.
     *
     * Following is an example of a simple usage:
     *
     *   eachFileOrDirectory('test/', function(err, file, stat) {
     *     if (err) throw err;
     *     if (!stat.isDirectory()) {
     *       console.log(">> Found file: " + file);
     *     }
     *   });
     *
     * Following is an example that waits for all files and directories to be 
     * scanned and then uses the entire result to do something:
     *
     *   eachFileOrDirectory('test/', null, function(files, stats) {
     *     if (err) throw err;
     *     var len = files.length;
     *     for (var i = 0; i < len; i++) {
     *       if (!stats[i].isDirectory()) {
     *         console.log(">> Found file: " + files[i]);
     *       }
     *     }
     *   });
     */
    var eachFileOrDirectory = function(directory, fileHandler, completeHandler) {
      var filesToCheck = 0;
      var checkedFiles = [];
      var checkedStats = [];
    
      directory = (directory) ? directory : './';
    
      var fullFilePath = function(dir, file) {
        return dir.replace(/\/$/, '') + '/' + file;
      };
    
      var checkComplete = function() {
        if (filesToCheck == 0 && completeHandler) {
          completeHandler(null, checkedFiles, checkedStats);
        }
      };
    
      var onFileOrDirectory = function(fileOrDirectory) {
        filesToCheck++;
        fs.stat(fileOrDirectory, function(err, stat) {
          filesToCheck--;
          if (err) return fileHandler(err);
          checkedFiles.push(fileOrDirectory);
          checkedStats.push(stat);
          fileHandler(null, fileOrDirectory, stat);
          if (stat.isDirectory()) {
            onDirectory(fileOrDirectory);
          }
          checkComplete();
        });
      };
    
      var onDirectory = function(dir) {
        filesToCheck++;
        fs.readdir(dir, function(err, files) {
          filesToCheck--;
          if (err) return fileHandler(err);
          files.forEach(function(file, index) {
            file = fullFilePath(dir, file);
            onFileOrDirectory(file);
          });
          checkComplete();
        });
      }
    
      onFileOrDirectory(directory);
    };
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to be able to perform some logic in the table.modifiedField method
I would like to post-process my app.config file and perform some token replacements after
I have a Window with a TextView, and I would like to perform some
I would like to use client-side Javascript to perform a DNS lookup (hostname to
I need to perform Diffs between Java strings. I would like to be able
I would like to implement a post build event that performs the following actions
Would like to get a list of advantages and disadvantages of using Stored Procedures.
Would like to create a strong password in C++. Any suggestions? I assume it
I would like to test a string containing a path to a file for
I would like to sort an array in ascending order using C/C++ . The

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.