Last active
August 29, 2015 14:12
-
-
Save mixmix/519e27028536d86149df to your computer and use it in GitHub Desktop.
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
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)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 likereaddir
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
andresult
(which you can name to whatever you like when defining your callback functions).fs.readdir(pathname, sort_print(err,list))
errors because you are callingsort_print
buterr
andlist
are not defined at the time you are calling (they will be defined inside of sort_print but not necessarily outside). you could dosort_print(null, ['file.ext'])
and that would work, as that's similar to howfs.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.