Skip to content

Instantly share code, notes, and snippets.

@dengjonathan
Created August 28, 2016 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dengjonathan/c8c576f4532cfb64354bb946ffacc561 to your computer and use it in GitHub Desktop.
Save dengjonathan/c8c576f4532cfb64354bb946ffacc561 to your computer and use it in GitHub Desktop.
Idiomatic Node async call with eror handling
// this is an idiomatic example of a Node async call with callbacks that
// handle both returned data and error
/***********This is the module defined for later use */
var fs = require('fs');
module.exports = function(file, ext, callback) {
fs.readdir(file, function(err, data) {
// if readdir returns error, call callback with error early
if (err) {
return callback(err);
}
// if readdir returns with data, do some stuff with it
data = data.filter(function(each) {
return each.split('.')[1] === ext;
});
// then call callback with data (error is null because we already checked)
return callback(null, data);
});
};
/***This is the program that calls the module above**/
var module = require('./module.js');
// file path is from enviroment variable passed in through CLI
var file = process.argv[2];
var ext = process.argv[3];
// idiomatic callback functions have error handling
var callback = function(err, data) {
if (err) {
return console.error('there was an I/O error');
} else {
data.forEach(function(each) {
console.log(each);
});
}
};
module(file, ext, callback);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment