Skip to content

Commit 6f0fe3f

Browse files
authored
Getting Started in Node.js (#2116)
1 parent ef19698 commit 6f0fe3f

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

docs/getting-started.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,36 @@ Here’s an example of client-side rendering in Svelte. For server-side renderin
319319
:::
320320

321321
See our [Plot + Svelte REPL](https://svelte.dev/repl/ebf78a6a6c1145ecb84cf9345a7f82ae?version=4.2.0) for details.
322+
323+
## Plot in Node.js
324+
325+
You can use Plot to server-side render SVG or PNG in Node.js. Use [JSDOM](https://github.com/jsdom/jsdom) for a DOM implementation via the **document** option, then serialize the generated plot using **outerHTML**.
326+
327+
```js
328+
import {readFile} from "node:fs/promises";
329+
import * as Plot from "@observablehq/plot";
330+
import * as d3 from "d3";
331+
import {JSDOM} from "jsdom";
332+
333+
const penguins = d3.csvParse(await readFile("./penguins.csv", "utf-8"), d3.autoType);
334+
335+
const plot = Plot.plot({
336+
document: new JSDOM("").window.document,
337+
marks: [
338+
Plot.dot(penguins, {x: "culmen_length_mm", y: "culmen_depth_mm", stroke: "species"})
339+
]
340+
});
341+
342+
plot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "http://www.w3.org/2000/svg");
343+
plot.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
344+
345+
process.stdout.write(plot.outerHTML);
346+
```
347+
348+
To rasterize SVG as PNG, you could use [canvg](https://github.com/canvg/canvg) and [node-canvas](https://github.com/Automattic/node-canvas), or [sharp](https://sharp.pixelplumbing.com/):
349+
350+
```js
351+
process.stdout.write(await sharp(Buffer.from(plot.outerHTML, "utf-8")).png().toBuffer());
352+
```
353+
354+
For better font rendering, consider [Puppeteer](https://pptr.dev/).

0 commit comments

Comments
 (0)