Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!