【问题标题】:How to read svg path string from svg file in Node.Js如何从 Node.Js 中的 svg 文件中读取 svg 路径字符串
【发布时间】:2022-07-24 19:56:45
【问题描述】:

我有一个应用程序,我需要从存储在 Node.Js 的文件系统中的 svg 文件中解析 svg 路径字符串。我尝试使用 cheerio 模块获取 svg 路径字符串,但使用它我只能获得第一个路径字符串

    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');

但我的 svg 文件有三个路径

为了完成获取整个 svg 字符串路径的任务,我需要获取整个 svg 字符串路径。 如果有人有任何解决方案让我从 Node.Js 中的 svg 文件中解析 svg 字符串路径,我将不胜感激。

【问题讨论】:

标签: node.js svg cheerio


【解决方案1】:

在获得$('path') 值后,您可以使用.each 获得这三个值。

代码:

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

【讨论】:

    猜你喜欢
    • 2017-08-19
    • 1970-01-01
    • 2016-03-14
    • 2014-09-14
    • 2019-12-13
    • 2013-01-14
    • 2012-08-20
    • 1970-01-01
    • 2012-04-25
    相关资源
    最近更新 更多