How to use D3js on server side to generate SVG directly?

You may look this post. in these posts, some similar question has reached the answer.

D3js: how to generate standalone SVG files? (Nodejs)

Exporting D3.js graphs to static SVG files, programmatically

Hope these help and others come to answer.


I made an example in case that helps:

#!/usr/bin/env node
var d3 = require("d3"),
    jsdom = require("jsdom");

const { JSDOM } = jsdom;

const { document } = (new JSDOM('')).window;
global.document = document;

var body = d3.select(document).select("body");

var width = 300;
var height = 300;
var svg = body.append("svg")
    .attr("width", width)
    .attr("height", height);
svg.append("line")
    .attr("x1", 100)
    .attr("y1", 100)
    .attr("x2", 200)
    .attr("y2", 200)
    .style("stroke", "rgb(255,0,0)")
    .style("stroke-width", 2);

const fs = require('fs');
fs.writeFileSync("test.svg", body.node().innerHTML)