0

I want to read the content of input (a folder) and push the result into input2 (an array):

 const input = process.argv[2]
 var input2 = []

 if (process.argv.length < 3) {
   console.log('Usage: node ' + process.argv[1] + ' FILENAME')
   process.exit(1)
 }

 fs.readdir(__dirname + `/${input}/`, (err, files) => {
    if (err) {
      console.log(err)
      return
    }

    files.forEach((file) => {
      console.log(file)
      fs.readFile(__dirname + `/${input}/` + file, 'utf8', (err, data) => {
        if (err) {
          console.log(err)
        }
        console.log(data)
        input2.push(data)
      })
    })
  })

 console.log(input2)

console.log(data) does log the values:

## Chapter 1

Paragrhap 1

## Chapter 2

Paragrhap 2

But console.log(input2) logs []

What am I doing wrong?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
alexchenco
  • 53,565
  • 76
  • 241
  • 413

1 Answers1

-1

you must write the console.log in end of foreach

 const input = process.argv[2]
 var input2 = []

if (process.argv.length < 3) {
console.log('Usage: node ' + process.argv[1] + ' FILENAME')
process.exit(1)
}

fs.readdir(__dirname + `/${input}/`, (err, files) => {
    if (err) {
      console.log(err)
      return
    }

files.forEach((file) => {
  console.log(file)
  fs.readFile(__dirname + `/${input}/` + file, 'utf8', (err, data) => {
    if (err) {
      console.log(err)
    }
    console.log(data)
    input2.push(data)
  })
})
 console.log(input2)

})

user3227295
  • 2,168
  • 1
  • 11
  • 17