Tue, 14. May 2013
Listen.js is an open source JavaScript library that makes it easy to wait for mutliple Node-style callbacks and process the results. For Node.js and the browser.
Listen.js is a tiny library focused on creating Node-style callbacks and wait for them to return. These features are implemented on top:
I'll explained in more detail in this post, but first of all, what does v1.0.0 mean?
The version numbers follow the semanitic versioning convention. That means, the API will stay 100% backward compatible in future releases. In fact, there are no plans yet to add new features, but I will do bug fix releases and have an open ear for suggestions. Please to provide feedback below this post or in the issue tracker on GitHub.
Yes. The source code is released under the MIT license. Feel free to use, modify and bundle it with your stuff.
As an example, let's assume you want to read all files in a directory in parrallel and then process the file contents.
var listen = require('listen');
var fs = require('fs');
fs.readdir('some/dir', function (err, files) {
if (err) {
throw err;
}
var listener = listen();
files.forEach(function (file) {
fs.readFile(file, listener());
});
listener.then(function (err, fileContents) {
// 'fileContents' is an Array with the same order as 'files'
});
});
Assuming you want to read a JSON and an HTML file in parallel, it reads nicer to refer to the files by a name rather than using the results object as an array.
var listener = listen();
fs.readFile('some.json', listener('json'));
fs.readFile('some.html', listener('html'));
listener.then(function (err, results) {
console.log('JSON:', results.json);
console.log('HTML:', results.html);
});
Listen has a special error type named ErrorList
. If more than one callback
is invoked with an error, an ErrorList
is created that lists the actual
errors.
Another custom error provided by listen.js is TimeoutError
which may be
returned if you specified a timeout.
In case you don't want to wait for a longer running task, e.g. a network bound
operation, you can define a timeout after which the callback is invoked with a
TimeoutError
.
var listener = listen();
expensiveOperation(listener(5000));
listener.then(function (err) {
if (err && err.name === 'TimeoutError') {
console.warn('Timeout after 5 seconds!');
}
});
The full documentation is on the project page.
There are standalone browser packages available for download. You can also run the unit tests in your browser. The test cases all pass on Node.js 0.6, 0.8 and 0.10.
Node packages can be installed using NPM:
npm install listen
The NPM package can also be used with Browserify to bundle it directly with your code.
Please star listen.js on GitHub.
Thanks for reading!
Questions? Leave a comment.