Last active
November 13, 2022 18:21
-
-
Save benoitv-code/148eadcfde3e978a1ad1d3ec9e2a7265 to your computer and use it in GitHub Desktop.
d3, jsdom, node.js: server-side rendering
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Instructions: | |
// npm install --save d3 jsdom | |
const fs = require('fs'); | |
const d3 = require('d3'); | |
const jsdom = require('jsdom'); | |
const { JSDOM } = jsdom; | |
const fakeDom = new JSDOM('<!DOCTYPE html><html><body></body></html>'); | |
const outputLocation = './output.svg'; | |
let body = d3.select(fakeDom.window.document).select('body'); | |
// Make an SVG Container | |
let svgContainer = body.append('div').attr('class', 'container') | |
.append("svg") | |
.attr("width", 1280) | |
.attr("height", 1024); | |
// Draw a line | |
let circle = svgContainer.append("line") | |
.attr("x1", 5) | |
.attr("y1", 5) | |
.attr("x2", 500) | |
.attr("y2", 500) | |
.attr("stroke-width", 2) | |
.attr("stroke", "black"); | |
// Output the result to console | |
console.log(body.select('.container').html()); | |
// Output the result to file | |
fs.writeFileSync(outputLocation, body.select('.container').html()); |
Hie, I was trying to implement the same to my project and its throwing the following error -
"Cannot find module 'd3'"
I'm pretty certain that its not able to detect d3 library which is installed in my local. Are you using d3 npm package or the standard javascript library ?
Hi @JoybasakQumaOne, it's using d3 from npm, the installation instructions are on top of the file: npm install --save d3 jsdom
it should now be https://gist.github.com/alexp1917/e2b62c89d929847aa3e3e8aecf9a3063
const d3 = import('d3');
async function main() {
// ...
// top level async is evil ...
let body = (await d3).select(fakeDom.window.document).select('body');
// ...
}
main();
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hie, I was trying to implement the same to my project and its throwing the following error -
"Cannot find module 'd3'"
I'm pretty certain that its not able to detect d3 library which is installed in my local. Are you using d3 npm package or the standard javascript library ?