A
A
atumbochka2021-05-06 21:36:46
Node.js
atumbochka, 2021-05-06 21:36:46

What is the correct way to use readdirSync?

There is the following code:

app.get("/data", (req, res) => {
  const files = fs.readdirSync(path.join(__dirname, "uploads"))
  const array = []
  files.forEach(file => {
    array.push(file.fileName)
  })
  res.send(JSON.stringify({"arr": array}))
})

In it, I want to send file names to the page, but I get an empty array. As far as I understand, readdirSync returns an array with files, therefore, I use the fileName method that files have, but for some reason it does not work out. How can this be fixed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-05-06
@atumbochka

need to use asynchronous method

fs.readdir(path.resolve(__dirname, "uploads"), (err, files) => {
  console.log(files)
})

and in the callback do what you need with the files
and handle errors

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question