1

I can access the global variable within the function, but when I push it does not set to the global variable. What am I doing wrong?

const fs = require('fs')
const moviesDir = `./movies`

var moviesList = []

function getMoviesList() {
  fs.readdir(moviesDir, (error, movies) => {
    movies.forEach(movie => {
      console.log(movie)  // <--works
      moviesList.push(movie)
    })
console.log(moviesList) // <--works
  })
}
getMoviesList()

console.log(moviesList) // <-- does-not work
jasenmichael
  • 388
  • 5
  • 17

1 Answers1

1

readdir is asynchronous, meaning that the final console log may be happening before your callback is executed. You can prevent this by using fs.readdirSync instead

Billy Reilly
  • 1,422
  • 11
  • 11