or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdindex.mdnodejs-api.md

nodejs-api.mddocs/

0

# Node.js API

1

2

The Node.js API provides programmatic access to Mermaid diagram rendering capabilities. It offers both high-level functions for common operations and low-level functions for fine-grained control over the rendering process.

3

4

## Capabilities

5

6

### High-Level Rendering Function

7

8

The primary function for rendering Mermaid diagrams from Node.js applications.

9

10

```javascript { .api }

11

/**

12

* Renders a mermaid diagram or processes a markdown file

13

* @param input - Input file path, undefined for stdin

14

* @param output - Output file path or "/dev/stdout" for stdout

15

* @param options - Optional configuration

16

* @returns Promise that resolves when rendering is complete

17

*/

18

async function run(

19

input: string | undefined,

20

output: string,

21

options?: RunOptions

22

): Promise<void>;

23

24

interface RunOptions {

25

puppeteerConfig?: LaunchOptions;

26

quiet?: boolean;

27

outputFormat?: "svg" | "png" | "pdf";

28

parseMMDOptions?: ParseMDDOptions;

29

artefacts?: string;

30

}

31

```

32

33

**Usage Examples:**

34

35

```javascript

36

import { run } from "@mermaid-js/mermaid-cli";

37

38

// Basic diagram rendering

39

await run("diagram.mmd", "output.svg");

40

41

// Render to PNG with custom options

42

await run("flowchart.mmd", "flowchart.png", {

43

outputFormat: "png",

44

parseMMDOptions: {

45

backgroundColor: "transparent",

46

mermaidConfig: { theme: "dark" }

47

}

48

});

49

50

// Process markdown file

51

await run("README.md", "README-processed.md", {

52

artefacts: "./diagrams"

53

});

54

55

// Read from stdin equivalent (input = undefined)

56

await run(undefined, "output.svg", {

57

quiet: true

58

});

59

60

// Render with custom Puppeteer config

61

await run("input.mmd", "output.pdf", {

62

puppeteerConfig: {

63

headless: "shell",

64

args: ["--no-sandbox"]

65

},

66

parseMMDOptions: {

67

pdfFit: true

68

}

69

});

70

```

71

72

### Low-Level Rendering Function

73

74

Direct rendering function that works with an existing Puppeteer browser instance for better performance when rendering multiple diagrams.

75

76

```javascript { .api }

77

/**

78

* Render a single mermaid diagram using an existing browser instance

79

* @param browser - Puppeteer browser or browser context

80

* @param definition - Mermaid diagram definition string

81

* @param outputFormat - Output format

82

* @param options - Rendering options

83

* @returns Promise with rendered data and metadata

84

*/

85

async function renderMermaid(

86

browser: Browser | BrowserContext,

87

definition: string,

88

outputFormat: "svg" | "png" | "pdf",

89

options?: ParseMDDOptions

90

): Promise<RenderResult>;

91

92

interface RenderResult {

93

title: string | null; // SVG title element content

94

desc: string | null; // SVG description element content

95

data: Uint8Array; // Rendered diagram data

96

}

97

```

98

99

**Usage Examples:**

100

101

```javascript

102

import { renderMermaid } from "@mermaid-js/mermaid-cli";

103

import puppeteer from "puppeteer";

104

import fs from "fs/promises";

105

106

const browser = await puppeteer.launch({ headless: "shell" });

107

108

try {

109

// Render multiple diagrams with same browser instance

110

const diagram1 = `

111

graph TD

112

A[Start] --> B[Process]

113

B --> C[End]

114

`;

115

116

const diagram2 = `

117

sequenceDiagram

118

Alice->>Bob: Hello

119

Bob-->>Alice: Hi there

120

`;

121

122

const result1 = await renderMermaid(browser, diagram1, "svg", {

123

backgroundColor: "white",

124

mermaidConfig: { theme: "default" }

125

});

126

127

const result2 = await renderMermaid(browser, diagram2, "png", {

128

backgroundColor: "transparent",

129

viewport: { width: 1200, height: 800, deviceScaleFactor: 2 }

130

});

131

132

// Save results

133

await fs.writeFile("diagram1.svg", result1.data);

134

await fs.writeFile("diagram2.png", result2.data);

135

136

// Access metadata

137

console.log("Diagram 1 title:", result1.title);

138

console.log("Diagram 1 description:", result1.desc);

139

140

} finally {

141

await browser.close();

142

}

143

```

144

145

### CLI Function

146

147

Programmatically invoke the CLI functionality.

148

149

```javascript { .api }

150

/**

151

* Main CLI function that parses command line arguments and executes rendering

152

* Reads from process.argv and handles all CLI options

153

* @returns Promise that resolves when CLI execution is complete

154

*/

155

async function cli(): Promise<void>;

156

```

157

158

**Usage Examples:**

159

160

```javascript

161

import { cli } from "@mermaid-js/mermaid-cli";

162

163

// Programmatically invoke CLI (reads from process.argv)

164

// Useful for custom CLI wrappers

165

await cli();

166

```

167

168

### Error Handling Function

169

170

Utility function for consistent error handling and process termination.

171

172

```javascript { .api }

173

/**

174

* Prints error message to stderr and exits with code 1

175

* @param message - Error message to display (string or any value)

176

* @returns Never returns (exits process)

177

*/

178

function error(message: any): never;

179

```

180

181

**Usage Examples:**

182

183

```javascript

184

import { error } from "@mermaid-js/mermaid-cli";

185

186

// Handle custom validation errors

187

if (!inputFile.endsWith('.mmd')) {

188

error("Input file must have .mmd extension");

189

}

190

191

// Handle caught exceptions

192

try {

193

await someOperation();

194

} catch (err) {

195

error(`Operation failed: ${err.message}`);

196

}

197

```

198

199

## Configuration Types

200

201

### Core Types

202

203

```javascript { .api }

204

// Puppeteer types used by the API

205

interface Browser {

206

// Puppeteer browser instance

207

close(): Promise<void>;

208

newPage(): Promise<Page>;

209

}

210

211

interface BrowserContext {

212

// Puppeteer browser context instance

213

close(): Promise<void>;

214

newPage(): Promise<Page>;

215

}

216

217

interface LaunchOptions {

218

// Puppeteer launch configuration

219

headless?: boolean | "shell";

220

args?: string[];

221

timeout?: number;

222

executablePath?: string;

223

[key: string]: any;

224

}

225

226

interface Viewport {

227

width: number;

228

height: number;

229

deviceScaleFactor?: number;

230

}

231

```

232

233

### ParseMDDOptions

234

235

Comprehensive options for controlling diagram rendering behavior.

236

237

```javascript { .api }

238

interface ParseMDDOptions {

239

/** Viewport settings for browser rendering */

240

viewport?: Viewport;

241

242

/** Background color for PNG/SVG outputs */

243

backgroundColor?: string | "transparent";

244

245

/** Mermaid configuration object */

246

mermaidConfig?: {

247

theme?: "default" | "forest" | "dark" | "neutral";

248

themeVariables?: object;

249

flowchart?: object;

250

sequence?: object;

251

gantt?: object;

252

[key: string]: any;

253

};

254

255

/** Custom CSS to inject into the diagram */

256

myCSS?: string;

257

258

/** Scale PDF output to fit chart dimensions */

259

pdfFit?: boolean;

260

261

/** SVG element ID attribute */

262

svgId?: string;

263

264

/** Icon packs to load (Iconify NPM package names) */

265

iconPacks?: string[];

266

}

267

```

268

269

**Usage Examples:**

270

271

```javascript

272

const options = {

273

viewport: {

274

width: 1600,

275

height: 1200,

276

deviceScaleFactor: 2

277

},

278

backgroundColor: "#f8f9fa",

279

mermaidConfig: {

280

theme: "dark",

281

themeVariables: {

282

primaryColor: "#ff6b6b",

283

primaryTextColor: "#ffffff"

284

},

285

flowchart: {

286

useMaxWidth: true,

287

htmlLabels: true

288

}

289

},

290

myCSS: `

291

.node rect {

292

stroke-width: 3px;

293

border-radius: 8px;

294

}

295

`,

296

pdfFit: true,

297

svgId: "my-custom-diagram",

298

iconPacks: ["@iconify-json/logos", "@iconify-json/mdi"]

299

};

300

301

await run("input.mmd", "output.png", { parseMMDOptions: options });

302

```

303

304

### Markdown Processing Types

305

306

Types related to markdown file processing and image generation.

307

308

```javascript { .api }

309

interface MarkdownImageProps {

310

/** Path to the generated image file */

311

url: string;

312

313

/** Alt text for the image (required for accessibility) */

314

alt: string;

315

316

/** Optional title text for the image */

317

title?: string | null;

318

}

319

```

320

321

## Error Handling

322

323

The Node.js API throws standard JavaScript errors that should be caught and handled appropriately.

324

325

**Common Error Scenarios:**

326

327

```javascript

328

import { run, renderMermaid } from "@mermaid-js/mermaid-cli";

329

330

try {

331

await run("nonexistent.mmd", "output.svg");

332

} catch (error) {

333

if (error.code === 'ENOENT') {

334

console.error("Input file not found");

335

} else {

336

console.error("Rendering failed:", error.message);

337

}

338

}

339

340

// Handle invalid Mermaid syntax

341

try {

342

const result = await renderMermaid(browser, "invalid syntax", "svg");

343

} catch (error) {

344

console.error("Invalid Mermaid diagram:", error.message);

345

}

346

347

// Handle Puppeteer launch failures

348

try {

349

await run("input.mmd", "output.svg", {

350

puppeteerConfig: { executablePath: "/invalid/path" }

351

});

352

} catch (error) {

353

console.error("Browser launch failed:", error.message);

354

}

355

```

356

357

## Performance Considerations

358

359

When rendering multiple diagrams, reuse the browser instance for better performance:

360

361

```javascript

362

import { renderMermaid } from "@mermaid-js/mermaid-cli";

363

import puppeteer from "puppeteer";

364

import fs from "fs/promises";

365

366

const browser = await puppeteer.launch();

367

368

// Efficient batch processing

369

const diagrams = ["diagram1.mmd", "diagram2.mmd", "diagram3.mmd"];

370

const results = await Promise.all(

371

diagrams.map(async (diagramPath) => {

372

const definition = await fs.readFile(diagramPath, "utf8");

373

return renderMermaid(browser, definition, "svg");

374

})

375

);

376

377

await browser.close();

378

```

379

380

Use the high-level `run` function for simple one-off operations:

381

382

```javascript

383

// For single diagram conversions

384

await run("simple-diagram.mmd", "output.svg");

385

```