如何在html文件中替换多个标签的内容? [Node.js的]

时间:2014-01-12 19:44:46

标签: javascript html node.js templates

我们有html文件:

<div class="my1">MY1</div>
<h1 class="my2">MY2</h1>
<p class="my3">MY3</p>
<div class="my2">MY2</div>
带有替换值的

和json-file:

{
    "my1":"new my1",
    "my2":"new my2",
    "my3":"new my3"
}

结果必须是带有新值的新html文件。

怎么做?没有DOM!

2 个答案:

答案 0 :(得分:7)

我不明白为什么你反对DOM建设,因为它很容易做到相对论。有一些轻量级模块,如cheerio,可以满足您的要求,并有一个简单的API(类似于JQuery)。

完全正常的例子

此示例使用cheerio node module完全符合您的要求。

文件

<强> replace.js

var fs = require('fs')
, cheerio = require('cheerio');

// html file we are working on
var htmlPath = __dirname + '/htmlFile.html';
// html file to output modified html to
var outPath = __dirname + '/htmlFixed.html';

// load in the json file with the replace values
var replaceValues = require('./replaceValues.json');

fs.readFile(htmlPath, {encoding: 'utf8'}, function(error, data) {
    var $ = cheerio.load(data); // load in the HTML into cheerio

    for (var key in replaceValues) {
        // the keys are class names, use them to pick out what element
        // we are going to modify & then replace the innerHTML content
        // of that element
        $('.' + key).html(replaceValues[key]);
    }

    fs.writeFile(outPath, $.html());
});

<强> htmlFile.html

<div class="my1">MY1</div>
<h1 class="my2">MY2</h1>
<p class="my3">MY3</p>
<div class="my2">MY2</div>

<强> replaceValues.json

{
    "my1":"new my1",
    "my2":"new my2",
    "my3":"new my3"
}

用法

node replace.js

结果

运行脚本后,您将在与名为htmlFixed.html的原始HTML文件相同的目录中创建一个新文件,并对内容执行更改:

<div class="my1">new my1</div>
<h1 class="my2">new my2</h1>
<p class="my3">new my3</p>
<div class="my2">new my2</div>

答案 1 :(得分:1)

Node.js没有任何文档对象模型的概念(即DOM) - "Why doesn't node.js have a native DOM?" - 因此无法访问实例化HTML元素的方法(这对于有权访问以解析你的HTML。)

因此,您必须导入一个库以用作解析器(就像处理html时所需的任何其他服务器端实现一样 - don't regex it!)。

目前这样做的领导者是 jsDOM