[Fixed] Adding multiple objects into one response| Express.js

Issue

Im trying to return a list of files in a directory. can anyone help with this?

   
const directoryPath = path.join(__dirname, "./DB/public")

fs.readdir(directoryPath, function(err, files) {
  if (err) {
    console.log("Error getting directory information.")
  } else {
    files.forEach(function(file) {
      console.log(file)
      res.send(file)
    })
  }
})
});```

Solution

If you want just a list of file name, all you have to do is to gather file names first, and then send an array of files as a response.

const directoryPath = path.join(__dirname, "./DB/public")

fs.readdir(directoryPath, function(err, files) {
  if (err) {
    console.log("Error getting directory information.")
  } else {
    res.send(files)
  }
})
});

If you want to transfer actual files, then it’s a different story. If you want to transfer files, please ask another question with more detail.

Leave a Reply

(*) Required, Your email will not be published