Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Return File Data With A Custom Function

I am building my own project (website) and I am trying to create a renderTemplate function to return HTML files but I don't how to return data from the file

Here is quick example of what I am doing

var file = require("fs")

const render = () => {
    file.readFile(`file.txt`, {encoding: "utf-8"}, (err, data) => {
        if (err) throw err
        return data
    })
}

console.log(render())

I made sure the file.txt exists, ran the code and got undefined in the output

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Because render doesn not return anything, and it can't return anything since you are using the asynchronous callback based version of readFile.

Or you use the sync version:

const fs = require("fs")

const render = () => fs.readFileSync(`file.txt`, {encoding: "utf-8"})

console.log( render() )

Or you use promise based async version that is better if you have multiple readings:

const fs = require("fs")

const render = () => fs.readFileAsync(`file.txt`, {encoding: "utf-8"})

render().then( data => console.log(data) )
about 4 years ago · Juan Pablo Isaza Relatório

0

Since there is no return in your function, it returns undefined. You can try readFileSync

Example:

 const render = () => file.readFileSync("file.txt" , { encoding: "utf-8" });
 console.log(render())

or

 const render = () => {
   return new Promise((resolve, reject) => {
     file.readFile(`file.txt`, { encoding: "utf-8" }, (err, data) => {
        if (err) reject(err);
        resolve(data);
     });
   });  
 }; 

 render().then(console.log)
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda