Home > Blockchain >  fs.readFileSync & path
fs.readFileSync & path

Time:01-25

I am relatively new to Node.js and have been looking around but cannot find a solution.

I want to read files from a subfolder 'filesPath'. I don't know how to write fs.readFileSync correctly

That is my idea. It works as let pdffile = fs.readFileSync(files[i]), but does not works as let pdffile = fs.readFileSync(filesPath, files[i]). Can you help me?

In example array is empty, but I cllect them in previous step.

var fs = require('fs')

const filesPath = path.join(__dirname, '/downloaded_files')
var files = []

function getNumbersAndPin() {
for (let i = 0; i < files.length; i  ) {
    let pdffile = fs.readFileSync(filesPath, files[i])
    //let pdffile = fs.readFileSync(files[i]) //It works but looks for files in __dirname

    pdfparse(pdffile).then(function (data) {
        console.log(data.text.slice(-23))
        })
    }
}
setTimeout(getNumbersAndPin, 3000)

CodePudding user response:

Check the documentation https://nodejs.org/api/fs.html#fsreadfilesyncpath-options. The second argument to readFileSync expects "options", not a file name or alike. Furthermore, your "files" array is empty.

CodePudding user response:

As mentioned in a comment, you need to call path.join again. From this:

let pdffile = fs.readFileSync(filesPath, files[i])

to

let filePath = path.join(filesPath, '/', files[i])
let pdffile = fs.readFileSync(filePath)
  • Related