Jaume Mal
Jaume Mal

Reputation: 658

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

Upvotes: 2

Views: 1832

Answers (3)

JESUS rose to life
JESUS rose to life

Reputation: 29

I had to use $.html() not $.xml()

Here is that in context based on this answer

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

Upvotes: 0

Jaume Mal
Jaume Mal

Reputation: 658

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

Upvotes: 2

ThirdOne
ThirdOne

Reputation: 1248

You could use the fs-cheerio package to write to files. In your code the original variable is not being modified. It is the parsed cheerio representation that gets modified.

Upvotes: 1

Related Questions