3

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.

mne_web_dev
  • 261
  • 4
  • 12
  • 1
    Get everything https://stackoverflow.com/questions/50058416/is-there-a-way-to-select-every-single-element-in-cheerio and iterate – Robert Longson Dec 05 '21 at 22:22
  • `const svgPath = $('path').attr('d');` needs to be [inside the asynchronous callback](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call), for starters. – ggorlen Sep 01 '23 at 18:42

1 Answers1

1

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);
});
Tim Affram
  • 56
  • 3
  • Minor point: I think `xml: true` replaces deprecated `xmlMode: true`, although I can't find it in the docs at the moment. An important part of this answer is that all of the code dependent on the file is inside the callback, one of OP's two problems. – ggorlen Sep 01 '23 at 19:45