0

Ok, so i made this function which reads a directory and checks each file to see if it is a file or a folder, if it is a file then return it to the array. Here:

function readDirr(dir){
  return fs.readdirSync(dir).filter(function(file){
    return fs.statSync(path.join(dir, file)).isFile(); 
  }); 
} 
console.log(readDirr("./uploads/")); //-> outputs a array of filenames 

So now i want to do the same just asynchronously. I have tried, but cant get it to work. Can anyone explain how to do this, preferably with promise? Thanks!

Edit: This is the function that i made:

function readDirr(dir){
  return fs.readdirAsync(dir)
  .then(function(files){
    files.forEach(function(file){
      if(fs.statAsync(path.join(dir, file)).isFile()){ //gives error here saying 'undefined is not a function'
        return file; 
      }
    })
  })
}
console.log(readDirr("./uploads/")); 

Output on the console is: { _bitField: 0, _fulfillmentHandler0: undefined, _rejectionHandler0: undefined, _promise0: undefined, _reciver0: undefined } And then gives an error in the if statement

Edir2: I trid this:

function readDirr(dir){
  return fs.readdirAsync(dir)
  .then(function(files){
    files.forEach(function(file){
      fs.statAsync(path.join(dir, file))
      .then(function(stat){
        if(stat.isFile()){
          return file; 
        }
      })
    })
  })
}

console.log(readDirr("./uploads/"));
It got rid of the error, but it comes out like this:

{ _bitField: 0,
  _fulfillmentHandler0: undefined,
  _rejectionHandler0: undefined,
  _promise0: undefined,
  _receiver0: undefined }

btw, i have no idea why this got marked as duplicate..

OlaStein
  • 25
  • 5
  • 2
    "I have tried, but cant get it to work" — Show us your attempt then we can tell you what the problem with it is. – Quentin Jun 17 '16 at 09:29
  • `fs.statAsync(path.join(dir, file))` will return a `Promise`.. Use `.then` handler.. – Rayon Jun 17 '16 at 09:46
  • You *cannot* `return` anything from an *asynchronous* function. `return` values are synchronous, asynchronous function results are asynchronous. You cannot get an asynchronous result from a function synchronously. That's why your question was closed as duplicate of an excellent post which explains this difference. – deceze Jun 17 '16 at 11:18
  • Ahaa, thank you! But just marking it as a duplicate is pretty rubbish. This question is not a duplicate of the linked question, and just marking it as a duplicate(without anyone telling me why) does not resolve my problem, but your comment did, so thank you. – OlaStein Jun 17 '16 at 13:01

0 Answers0