Home > Enterprise >  Get String from local SVG file in nodejs
Get String from local SVG file in nodejs

Time:08-10

I'm trying to get a String of an SVG file.

What I wanna get:

"<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>"

What I've tried:

const svgFile = await fsPromises.readFile(`./icons/${directoryName}/${iconName}`)
const serializer = new XMLSerializer()
const svgString = serializer.serializeToString(svgFile)
console.log(svgString)

Output: ReferenceError: XMLSerializer is not defined

CodePudding user response:

It seems that you are trying to use browser classes in node. Unless you are using another framework, such as Electron, this isn't possible out of the box.

However, there are often some libraries that can act as drop-in replacement.

For XMLSerializer, I found https://www.npmjs.com/package/xmlserializer.

If you are doing no further processing, you can also just directly read it to a string.

const svgString = await fsPromises.readFile(`./icons/${directoryName}/${iconName}`, "utf8");

Unlike the other answer, this is shorter.

CodePudding user response:

I found a pretty simple solution. Reading the file returns a Buffer which can then be converted to a String.

const svgFileData = await fsPromises.readFile(`./icons/${directoryName}/${iconName}`)
console.log(svgFileData.toString())
  • Related