In https://github.com/codyc4321/Flashcard-Generator I have a file where I want to split out the HTML generator into its own function.
The file is in js/main.js
. This callback:
function generate_html(cards_array) {
// https://stackoverflow.com/questions/7083045/fs-how-do-i-locate-a-parent-folder
var webpage_path = __dirname + '/../index_generated.html';
var template_path = __dirname + '/../index_template.html';
var html;
var html = fs.readFile(template_path, 'utf-8', function(error, source) {
var template = handlebars.compile(source);
var data = {
cards: cardsArr
}
return template(data);
});
return html
}
returns undefined
instead of the html generated by handlebars. How do I return html from this function?
It returns undefined
beause fs.readFile()
is asynchronously. Try with fs.readFileSync()
or use a callback function that is called in the fs.readFile()
response.
function generate_html(cards_array, cb) {
// https://stackoverflow.com/questions/7083045/fs-how-do-i-locate-a-parent-folder
var webpage_path = __dirname + '/../index_generated.html';
var template_path = __dirname + '/../index_template.html';
fs.readFile(template_path, 'utf-8', function(error, source) {
var template = handlebars.compile(source);
var data = {
cards: cardsArr
}
cb(template(data));
});
}
cb
is the callback function with a parameter for response.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.