Jay P
Jay P

Reputation: 626

append HTML from file with Cheerio, NodeJs

I am trying to append some html from a file to some existing html with cheerio but i keep getting errors (the errors are being produced by the cheerio library so debugging is hard)

expo.includeNav = function(html, result)
{
    var file = 'templates/admin_nav.html';

    fs.readFile(file, function(err, nav)
    {
        var $ = cheerio.load(html);
        $('body').append(nav);
        result($.html());

    });

}

It dosen't seem to like passing a variable into the append function.

If i put the html in instead of calling from a file it works, like so:

$('body').append('<div class="nav"> navigation list here</div>');

But i do not want that as i want front end devs to be able to edit an HTML file instead of digging into my node JS code to find where to change the html.

Upvotes: 1

Views: 4799

Answers (1)

Jay P
Jay P

Reputation: 626

I'v worked it out. I assume someone else may run into this issue as i could see it being a common need. so here is the answer.

You need to specify that you want it returned as a string instaed of a buffer. do this with 'utf8'

expo.includeNav = function(html, result)
{
    var file = 'templates/admin_nav.html';

    fs.readFile(file, 'utf8', function(err, nav)
    {
        var $ = cheerio.load(html);
        $('body').append(nav);
        result($.html());

    });

}

Upvotes: 3

Related Questions