Search code examples
javascriptnode.jsasynchronousfssynchronize

How can I use synchronize.js with node's fs.exists?


Node's fs.exists function does not follow the usual callback The callback gets only an argument with either true or false, instead of the usual error and result. Because of this, I can't figure out how to use it with sync.await.

Is there a simple way to use sync.await with functions that do not follow the normal node callback convention?

This code:

var alreadyExists = sync.await(fs.exists(fileName, sync.defer()));

results in the error:

Error: done() invoked with non-Error: true

because sync.defer() got a boolean in place of an error.

NOTE: Yes, fs.exists will be deprecated in the future. That is a different topic.


Solution

  • You can create a partial function from the deferred callback, where the err argument (the first one) is pre-filled as null:

    var defer         = sync.defer();
    var alreadyExists = sync.await(fs.exists(fileName, defer.bind(defer, null)));