0

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
codyc4321
  • 9,014
  • 22
  • 92
  • 165

1 Answers1

1

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.

CoursesWeb
  • 4,179
  • 3
  • 21
  • 27