Mark Smith
Mark Smith

Reputation: 1

Node app.js - Reading files synchronously?

I've been reading through example applications try to learning node. And I've noticed that several use the readdirSync method when loading models and controllers on boot().

For instance:

    var models_path = __dirname + '/app/models'
var model_files = fs.readdirSync(models_path)
model_files.forEach(function(file){
  if (file == 'user.js')
    User = require(models_path+'/'+file)
  else
    require(models_path+'/'+file)
})

This seems anti-node to me. It's the opposite of the "try-to-make-everything-async" that node favors.

When and why might synchronous file reads like this be a good idea?

Upvotes: 0

Views: 1020

Answers (2)

Julian Knight
Julian Knight

Reputation: 4923

Synchronous reads are needed when you have to be certain that all of the data is available before you continue AND you need to keep a sequence in order. In other words if you NEED to have the process blocked and unable to do anything else (for anyone) such as when you are starting up a server (e.g. reading the certificate files for HTTPS).

Synchronous reads may be desirable at other time to keep the coding simpler as Len has suggested. But then you are trading off simplicity with performance as you suggest. In fact, it is better to make use of one of the many sequencing helper libraries in this case. These greatly simplify your code by taking care of nested callbacks and sequence issues.

And of course, the code you provide as an example is rather dangerous - what happens if the read fails?

Here are 3 of the libraries:

  • Streamline.js Allows you to write async js/coffeescript as though it were sync. Simply replace the callbacks with '_'. BUT you either have to compile your scripts or run them via a loader.
  • async - seems to be about the best thought out and documented and is recommended by a couple of people who have built real-world apps.
  • async.js - Chainable, exposes fs as well (includes readdir, walkfiles, glob, abspath, copy, rm - focused on fs rather than generic

This link may also be of use: The Tale of Harry - An explanation of how a mythical programmer moves from traditional programming to callback-based & the patterns that he ends up using. Also a useful insight into the patterns presented in the async library.

Upvotes: 0

Asherah
Asherah

Reputation: 19347

More than likely, to make initialisation more simple—when asynchronicity for speed's sake doesn't matter; we're not trying to service many concurrent requests.

Similarly, if you need access to some variable which you're initialising on startup, which will be used for the life-time of the application, you don't want to have to wrap your entire app in a callback!

Upvotes: 3

Related Questions