So Im trying to use the nodejs express FS module to iterate a directory in my app, store each filename in an array, which I can pass to my express view and iterate through the l
I think it has to do with callback functions,
Exactly.
fs.readdir
makes an asynchronous request to the file system for that information, and calls the callback at some later time with the results.
So function (err, files) { ... }
doesn't run immediately, but console.log(myfiles)
does.
At some later point in time, myfiles
will contain the desired information.
You should note BTW that files
is already an Array, so there is really no point in manually appending each element to some other blank array. If the idea is to put together the results from several calls, then use .concat
; if you just want to get the data once, then you can just assign myfiles = files
directly.
Overall, you really ought to read up on "Continuation-passing style".