Using GoJS with Node.js

As of 2.0, GoJS can be used in DOM-less contexts like Node.js. However there are some considerations:

  • Since there is no Diagram DIV, you must instead set the Diagram.viewSize property. This affects all the same values as the DIV size, like Diagram.position and layout results from layouts that are viewport-sized.
  • Cannot measure go.Pictures, you must set a GraphObject.desiredSize instead.
  • Cannot measure go.TextBlocks accurately, you should set a GraphObject.desiredSize instead.

For server-side operations that need to measure Pictures or TextBlocks, you should consider using a headless browser with Node. Click here for examples using Node with Puppeteer (headless Chrome).

Node.js example

If you saved the following JavaScript as nodescript.js and run it with node (node nodescript.js), it will output Model JSON results in the console, which include the locations of laid-out Nodes. You can use Node.js in this way to do server-side operations like large layouts, and then send the JSON to the client.


// nodescript.js
// This example loads the GoJS library, creates a Diagram with a layout and prints the JSON results.

// Load GoJS.  This assumes using require and CommonJS:
const go = require("gojs");

const myDiagram =
  new go.Diagram('', // No DOM, so there can be no DIV!
    {
      viewSize: new go.Size(400,400), // Set this property in DOM-less environments
      layout: $(go.LayeredDigraphLayout)
    });

myDiagram.nodeTemplate =
  new go.Node('Auto',
      // specify the size of the node rather than measuring the size of the text
      { width: 80, height: 40 })
      // automatically save the Node.location to the node's data object
    .bindTwoWay('location', 'loc', go.Point.parse, go.Point.stringify)
    .add(
      new go.Shape('RoundedRectangle', { strokeWidth: 0})
        .bind('fill', 'color'),
      new go.TextBlock()
        .bind('text', 'key')
    );

// After the layout, output results:
myDiagram.addDiagramListener('InitialLayoutCompleted', () => console.log(myDiagram.model.toJson()) );

// load a model:
myDiagram.model = new go.GraphLinksModel(
[
  { key: 'Alpha', color: 'lightblue' },
  { key: 'Beta', color: 'orange' },
  { key: 'Gamma', color: 'lightgreen' },
  { key: 'Delta', color: 'pink' }
],
[
  { from: 'Alpha', to: 'Beta' },
  { from: 'Alpha', to: 'Gamma' },
  { from: 'Gamma', to: 'Delta' },
  { from: 'Delta', to: 'Alpha' }
]);

Alternatively, if your code is saved as nodescript.mjs or your project is of "type": "module", you can use GoJS as an ECMAScript module:


// nodescript.mjs
// This example loads the GoJS library, creates a Diagram with a layout and prints the JSON results.

// Load GoJS.  This assumes using import and ECMAScript modules:
import * as go from "gojs";

. . .