nodejs express fs iterating files into array or object failing

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

    I faced the same problem, and basing on answers given in this post I've solved it with Promises, that seem to be of perfect use in this situation:

    router.get('/', (req, res) => {
      var viewBag = {}; // It's just my little habit from .NET MVC ;)
    
      var readFiles = new Promise((resolve, reject) => {
        fs.readdir('./myfiles/',(err,files) => {
          if(err) { 
            reject(err); 
          } else {
            resolve(files);
          }
        });
      });
    
      // showcase just in case you will need to implement more async operations before route will response
      var anotherPromise = new Promise((resolve, reject) => {
        doAsyncStuff((err, anotherResult) => {
          if(err) { 
            reject(err); 
          } else {
            resolve(anotherResult);
          }
        });
      });
    
      Promise.all([readFiles, anotherPromise]).then((values) => {
        viewBag.files = values[0];
        viewBag.otherStuff = values[1];
        console.log(viewBag.files); // logs e.g. [ 'file.txt' ]
        res.render('your_view', viewBag);
      }).catch((errors) => {
        res.render('your_view',{errors:errors}); // you can use 'errors' property to render errors in view or implement different error handling schema
      });
    });
    

    Note: you don't have to push found files into new array because you already get an array from fs.readdir()'c callback. According to node docs:

    The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

    I belive this is very elegant and handy solution, and most of all - it doesn't require you to bring in and handle new modules to your script.

提交回复
热议问题