wyc
wyc

Reputation: 55323

Why is this fs loop reading the filenames but not their content?

What I want to do is to output the content of all the files in a folder:

  const fs = require('fs')
      , input = process.argv[2]



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

    files.forEach((file) => {
      console.log(file)

      fs.readFile(file, 'utf8', (err, data) => {
        console.log(data)
      })
    })
  })

But I'm puzzled console.log(file) do output the file names:

alex@alex-K43U:~/node/m2n/bin$ node index4.js folder
test.txt
test2.txt

But console.log(data) returns undefined:

alex@alex-K43U:~/node/m2n/bin$ node index4.js folder
undefined
undefined

What's happening here?

EDIT:

Maybe there's a problem with __dirname? This is my project structure:

enter image description here

Upvotes: 1

Views: 48

Answers (1)

antyrat
antyrat

Reputation: 27765

You need to pass full path to your filenames:

fs.readFile(__dirname + `/${input}/` + file, 'utf8', (err, data) => {

And I would recommend you to log errors so you will know next time what is happening wrong:

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

Upvotes: 3

Related Questions