Node.js 在节点上使用ChereIO修改后写入文件

Node.js 在节点上使用ChereIO修改后写入文件,node.js,fs,cheerio,Node.js,Fs,Cheerio,我正在运行一个节点脚本,该脚本读取.svg字体文件,将其作为字符串变量传递给Cheerio,修改它并尝试写入磁盘 问题是,尽管脚本似乎可以工作,但输出文件与输入文件相同,就好像没有进行任何修改一样 在我看来,我传递给cheerio的原始“svgFont”变量似乎根本没有修改 因此,我需要将修改传递回它,或者将cheerio的输出直接传递给fs write。但我不知道该怎么做 const cheerio = require('cheerio'); var fs = require('fs');

我正在运行一个节点脚本,该脚本读取.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!");
        });
});

您可以使用该包写入文件。在代码中,未修改原始变量。修改的是已解析的ChereIO表示。

正确的答案是传递包含所有修改的ChereIO对象“$”,在本例中使用.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!");
    });