node.jsfscheerio

Writing to file after modifying with cheerio on node


I am running a node script that reads a .svg font file, passes it as a string variable to Cheerio, modifies it and attempts to write to disk

The problem is that although the script seems to work, the output file is identical to the input file, as if no modification happened.

It looks to me as if the original "svgFont" variable that I pass to cheerio is not modified at all.

So I would need to either pass the modifications back to it, or output from cheerio directly to fs write. But I can't see how to.

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!");
        });
});

Solution

  • The right answer is to pass the cheerio object '$' that contains all the modifications using, in this case, .xml(), as this is a .svg file I am reading. For example:

       // 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!");
        });