nodejs express fs iterating files into array or object failing

后端 未结 5 2463
我寻月下人不归
我寻月下人不归 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条回答
  •  萌比男神i
    2021-02-15 10:58

    As several have mentioned, you are using an async method, so you have a nondeterministic execution path.

    However, there is an easy way around this. Simply use the Sync version of the method:

    var myfiles = [];
    var fs = require('fs');
    
    var arrayOfFiles = fs.readdirSync('./myfiles/');
    
    //Yes, the following is not super-smart, but you might want to process the files. This is how:
    arrayOfFiles.forEach( function (file) {
        myfiles.push(file);
    });
    console.log(myfiles);
    

    That should work as you want. However, using sync statements is not good, so you should not do it unless it is vitally important for it to be sync.

    Read more here: fs.readdirSync

提交回复
热议问题