nodejs express fs iterating files into array or object failing

后端 未结 5 2233
我寻月下人不归
我寻月下人不归 2021-02-15 10:43

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

5条回答
  •  走了就别回头了
    2021-02-15 11:08

    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".

提交回复
热议问题