I asked an earlier question last week concerning something kinda similar to this and it was immediately closed as I was referenced to a question about Asynchronous JavaScript. I tried to follow what seemed like the favorable opinion to use an asynchronous callback function, especially when using things like the fs module. However This code still does not continue to work. Are callbacks and other asyncs (like async functions/await) inherently different, and would they be more appropriate for this problem?
I am trying to return a buffer that is an html that I create appending fs reads from head, main (routeString variable) and tail html files.
What I don't get is why I can console.log the html buffer in the renderPage function, but it won't return that same buffer. Am I not able to return a buffer? I am really confused and have been stuck on this for a while.
const createPage = (routeString, callback) => {
fs.readFile(`${__dirname}/head.html`, 'utf-8', (err, data) => {
let header = data;
fs.readFile(`${__dirname}/public${routeString}.html`, 'utf-8', (err, data) => {
let main = data;
fs.readFile(`${__dirname}/tail.html`, 'utf-8', (err, data) => {
let tail = data;
let page = header + main + tail;
return callback(page);
});
});
});
}
const renderPage = (result) => {
console.log(result); // html/buffer prints!!
return result;
}
let newPage = createPage('/training', renderPage); // string argument point to training.html when used in function
console.log(newPage); // undefined