Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

126
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda