使用 Cheerio、NodeJs 从文件中附加 HTML [英] append HTML from file with Cheerio, NodeJs

查看:26
本文介绍了使用 Cheerio、NodeJs 从文件中附加 HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用cheerio将文件中的一些html附加到一些现有的html中,但我不断收到错误(这些错误是由cheerio库产生的,因此调试很困难)

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());

    });

}

它似乎不喜欢将变量传递给 append 函数.

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

如果我将 html 放入而不是从文件中调用,它会起作用,如下所示:

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>');

但我不希望那样做,因为我希望前端开发人员能够编辑 HTML 文件,而不是深入研究我的节点 JS 代码以找到更改 html 的位置.

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.

推荐答案

我已经解决了.我认为其他人可能会遇到这个问题,因为我认为这是一个普遍的需求.所以这就是答案.

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.

您需要指定您希望它作为缓冲区的字符串返回.用'utf8'来做到这一点

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());

    });

}

这篇关于使用 Cheerio、NodeJs 从文件中附加 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆