-
-
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)) | |
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.
ok so this doesn't work , i get an error about err not being known
this does work :
but I don't understand why wholly. I am guess that
sort_print
is being passed around as a variable which happens to be a function and the.readdir
knows that it's just going to try and pump 2 arguments (an error,err
; some data,list
say) into this thingsort_print
and hope for the best?is that the correct interpretation?