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