Skip to content

Instantly share code, notes, and snippets.

@mixmix
Last active August 29, 2015 14:12
Show Gist options
  • Save mixmix/519e27028536d86149df to your computer and use it in GitHub Desktop.
Save mixmix/519e27028536d86149df to your computer and use it in GitHub Desktop.
var pathname = process.argv[2];
var extension = '.' + process.argv[3];
var fs = require('fs');
var path = require('path');
fs.readdir(pathname, function(err, list) {
var matches = list.filter( function(element) {
return path.extname(element) === extension;
});
for (var i=0; i<matches.length; i++) {
console.log(matches[i]);
}
})
// note there is a .forEach ... i wonder if this is a node function
/* why doesn't this work?
* gets some error about not knowing what err is when we call it in readdir :(
*/
var sort_print = function(err, list) {
var matches = list.filter( function(element) {
return path.extname(element) === extension;
});
for (var i=0; i<matches.length; i++) {
console.log(matches[i]);
}
}
fs.readdir(pathname, sort_print(err,list))
@ahdinosaur
Copy link

yes, sort_print is a function being passed around as a variable. a function used in this way is called a "callback" and is called when a function like readdir wants to return after doing some asynchronous process. in javascript, the interpreter never waits (also known as blocking) while an asynchronous function is being processed (like reading from the filesystem), instead it queues up callbacks to an event loop and calls the callbacks when the asynchronous function is ready to respond. these callback functions have a conventional form, they take two arguments: err and result (which you can name to whatever you like when defining your callback functions).

fs.readdir(pathname, sort_print(err,list)) errors because you are calling sort_print but err and list are not defined at the time you are calling (they will be defined inside of sort_print but not necessarily outside). you could do sort_print(null, ['file.ext']) and that would work, as that's similar to how fs.readdir will call it after successfully querying the filesystem.

as a side note, .forEach is an Array method defined by javascript, same as .filter.

hope that helps, feel free to ask more questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment