Promise - Read Javascript File

Asked

Viewed 45 times

-1

Good Morning, I’m a beginner in Javascript I’m having difficulty using Promise to read.txt file using Fs.readFile. Detail I’m only using ". js"

I did a callback all right with him but it turned into that Hell, and I wanted to move on to Promise. Even using 1.txt file on Promise I’m not getting it. I’m sure I’m missing a lot of things.

  • Set a Function with parameter to receive the path leaving the more generic function, returning a Promise.
  • Inside it I passed the call of the readFile that has a callback. I even tried to use a ternary, but without success. I’m having difficulties in using the . then and . catch so I didn’t even post.

Someone could help me please. I wanted this Promise to read the.txt file and display it. If possible also how can I read more than one.txt file: "arq1.txt", "arq2.txt", "arq3.txt"

const fs = require("fs")


function lerArquivo (caminho) {
    const readFile = caminho => {
        return new Promise ((resolve, reject) => {
            caminho = './arquivo.txt'
            fs.readFile (caminho,(error, res) => {
                if(error) throw new error('Arquivo Inválido')
                else resolve(readFile)
                // error ? reject (error) : resolve (res)
            })
        })
    }
    
}

1 answer

0

Your function is not returning anything. You arrow readFile = as a function but nothing is returned in 'readFile'.

Try:

function lerArquivo (caminho) {
        return new Promise ((resolve, reject) => {
           fs.readFile (caminho,(error, res) => {
                if(error) throw new error('Arquivo Inválido')
                else resolve(readFile)
                // error ? reject (error) : resolve (res)
            })
        })
    }
    

To read multiple files you only need a loop (with for, map, etc.). This should return you an array of omissions. To solve all for example and have a promisse with the data of the files (invert to promisse out of the array) use:

const arquivos = ["arq1.txt", "arq2.txt", "arq3.txt"].map(lerArquivo)
Promise.all(arquivos).then(function(arraydeArquivos){console.log(arraydeArquivos)})

If you are using Node you can use promisify that already transforms readfile into promisse. without you need to create an implementation.

const readFile = util.promisify(fs.readFile);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.