nodejs express fs iterating files into array or object failing

后端 未结 5 2271
我寻月下人不归
我寻月下人不归 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:01

    fs.readdir is asynchronous (as with many operations in node.js). This means that the console.log line is going to run before readdir has a chance to call the function passed to it.

    You need to either:

    Put the console.log line within the callback function given to readdir, i.e:

    fs.readdir('./myfiles/', function (err, files) { if (err) throw err;
      files.forEach( function (file) {
        myfiles.push(file);
      });
      console.log(myfiles);
    });
    

    Or simply perform some action with each file inside the forEach.

提交回复
热议问题