【问题标题】:Writing to file after modifying with cheerio on node在节点上使用cheerio 修改后写入文件
【发布时间】:2025-12-04 22:45:02
【问题描述】:

我正在运行一个节点脚本,它读取 .svg 字体文件,将其作为字符串变量传递给 Cheerio,对其进行修改并尝试写入磁盘

问题在于,虽然脚本似乎可以工作,但输出文件与输入文件完全相同,就好像没有发生任何修改一样。

在我看来,我传递给cheerio 的原始“svgFont”变量根本没有被修改。

所以我需要将修改传回给它,或者直接从cheerio 输出到fs write。但我不知道怎么做。

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

// read the svg font
fs.readFile('font.svg', function read(err, data) {
        if (err) {
            throw err;
        }
        // convert to string and pass to cheerio 
        var svgFont = data.toString();
        const $ = cheerio.load(svgFont, {
            normalizeWhitespace: true,
            xmlMode: true
        });

        // loop all glyph tags
        $("glyph").each(function(i,el){
          // modify things
        });

        // Finally write the font with the modified paths
        fs.writeFile("outFont.svg", svgFont, function(err) {
            if(err) {
                throw err;
            }
            console.log("The file was saved!");
        });
});

【问题讨论】:

    标签: node.js fs cheerio


    【解决方案1】:

    您可以使用fs-cheerio 包来写入文件。在您的代码中,原始变量没有被修改。被修改的是解析后的 Cheerio 表示。

    【讨论】:

      【解决方案2】:

      正确的答案是传递包含所有修改的cheerio 对象'$',在这种情况下,使用.xml(),因为这是我正在阅读的.svg 文件。例如:

         // Finally write the font with the modified paths
          fs.writeFile("outFont.svg", $.xml(), function(err) {
              if(err) {
                  throw err;
              }
              console.log("The file was saved!");
          });
      

      【讨论】: