How to read svg path string from svg file in Node.Js

Viewed 479

I have an application where I need to parse svg path string from svg file that is stored in file system with Node.Js. I've tried getting svg path string using cheerio module but with It I only get first path string

    const path_to_svg = __dirname + '/documents/' + 'potpis.svg';

    let $;

    fs.readFile(path_to_svg,'utf8',(err,data)=>{
        if(err) console.log(err);
        $ = cheerio.load(data,{ xmlMode : true });
    });

    const svgPath =  $('path').attr('d');

But my svg file has three paths

enter image description here

In order to accomplish task of getting whole svg string path I need to grab whole svg string path. If anyone has any solution for me to parse svg string path from svg file in Node.Js I would appreciate it.

1 Answers

You can get all three using .each after getting the $('path') value.

code:

const fs = require("fs");
const cheerio = require("cheerio");

const path_to_svg = __dirname + "/documents/" + "potpis.svg";

let $;
const pathStringsArray = [];

fs.readFile(path_to_svg, "utf8", (err, data) => {
  if (err) console.log(err);
  $ = cheerio.load(data, { xmlMode: true });

  const pathSet = $("path");
  pathSet.each(function () {//<------Get all paths here like a 'for each' loop
    const d = $(this).attr("d");//"d" attribute for current path in the loop
    pathStringsArray.push(d);
  });

  //you can now use your array of path strings
  console.log(pathStringsArray);
});
Related