user3048402
user3048402

Reputation: 1369

NodeJS require a function inside module exports?

I have created a function to register a new partial with handlebars. I don't want to have everything stuffed inside the same file, so I am using module exports to export the function.

home.js - Used to render views

var fs = require('fs');
var Handlebars = require('hbs');

// Directories, Files and other Variables
var viewsDir = __dirname + '/../views';

// Function Helpers
var renderHtml = require('./helpers/render_html')(fs, viewsDir);

exports.index = function(req, res) {

    renderHtml('main', 'head');
    renderHtml('main', 'body');

    res.render('layout', {
        blogTitle: "My Website",
        blogDescription: "Hello! This is a description :)"
    });
};

render_html.js - The function to register a handlebars partial

module.exports = function(fs, viewsDir) {
    var renderHtml = function(file, section) {
        var newSection, handlebarsTemplate;

        if (typeof section === undefined) {
            newSection = "htmlBody";
        } else if (section === "body") {
            newSection = "htmlHead";
        } else if (section === "head") {
            newSection = "htmlBody";
        }

        handlebarsTemplate = fs.readFileSync(viewsDir + '/' + file + '.html', 'utf8');
        Handlebars.registerPartial(newSection, handlebarsTemplate);
    };
};

Whenever I call "renderHtml()" it throws an error that the function is undefined. How do I proceed?

Upvotes: 1

Views: 1256

Answers (1)

Robert Messerle
Robert Messerle

Reputation: 3032

You never returned your renderHtml method. Try this:

module.exports = function(fs, viewsDir) {
    var renderHtml = function(file, section) {
        var newSection, handlebarsTemplate;
        if (typeof section === undefined) {
            newSection = "htmlBody";
        } else if (section === "body") {
            newSection = "htmlHead";
        } else if (section === "head") {
            newSection = "htmlBody";
        }
        handlebarsTemplate = fs.readFileSync(viewsDir + '/' + file + '.html', 'utf8');
        Handlebars.registerPartial(newSection, handlebarsTemplate);
    };
    return renderHtml;
};

Upvotes: 2

Related Questions