GraphLib is a JavaScript library for directed and undirected multi-graphs. It provides a comprehensive Graph data structure with support for compound graphs (hierarchical node relationships), multiple edges between nodes, and a complete suite of graph algorithms including shortest path, topological sorting, and strongly connected components.
npm install graphlibimport { Graph, json, alg, version } from "graphlib";For CommonJS:
const { Graph, json, alg, version } = require("graphlib");import { Graph, alg } from "graphlib";
// Create a new directed graph
const g = new Graph();
// Add nodes with optional labels
g.setNode("a", "Node A");
g.setNode("b", "Node B");
g.setNode("c", "Node C");
// Add edges with optional labels
g.setEdge("a", "b", "Edge A->B");
g.setEdge("b", "c", "Edge B->C");
g.setEdge("a", "c", "Edge A->C");
// Query the graph
console.log(g.nodes()); // ["a", "b", "c"]
console.log(g.edges()); // [{v:"a", w:"b"}, {v:"b", w:"c"}, {v:"a", w:"c"}]
// Use algorithms
const shortestPaths = alg.dijkstra(g, "a");
console.log(shortestPaths.c.distance); // 2 (via b)
const topOrder = alg.topsort(g);
console.log(topOrder); // ["a", "b", "c"]GraphLib is built around several key components:
Core graph data structure with comprehensive node and edge management, support for hierarchical relationships, and configurable graph properties.
class Graph {
constructor(opts?: {
directed?: boolean;
multigraph?: boolean;
compound?: boolean;
});
}Complete suite of graph algorithms including shortest paths, traversal methods, cycle detection, and topological sorting.
const alg = {
components(g: Graph): string[][],
dijkstra(g: Graph, source: string, weightFn?: Function, edgeFn?: Function): Object,
dijkstraAll(g: Graph, weightFn?: Function, edgeFn?: Function): Object,
dfs(g: Graph, vs: string | string[], order: "pre" | "post"): string[],
findCycles(g: Graph): string[][],
floydWarshall(g: Graph, weightFn?: Function, edgeFn?: Function): Object,
isAcyclic(g: Graph): boolean,
postorder(g: Graph, vs: string | string[]): string[],
preorder(g: Graph, vs: string | string[]): string[],
prim(g: Graph, weightFn: Function): Graph,
tarjan(g: Graph): string[][],
topsort(g: Graph): string[]
};Complete graph serialization and deserialization for persistence, network transfer, and interoperability.
const json = {
write(g: Graph): Object,
read(json: Object): Graph
};// Edge object format used throughout the API
interface EdgeObj {
v: string; // Source node ID
w: string; // Target node ID
name?: string; // Optional edge name (for multigraphs)
}
// Graph options for constructor
interface GraphOptions {
directed?: boolean; // Whether graph is directed (default: true)
multigraph?: boolean; // Whether multiple edges allowed (default: false)
compound?: boolean; // Whether hierarchical nodes supported (default: false)
}