Home > Net >  Return File Data With A Custom Function
Return File Data With A Custom Function

Time:04-21

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

CodePudding user response:

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) )

CodePudding user response:

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)
  • Related