Created
August 28, 2016 18:19
-
-
Save dengjonathan/c8c576f4532cfb64354bb946ffacc561 to your computer and use it in GitHub Desktop.
Idiomatic Node async call with eror handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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