# Node.js

## Content

<span style="color: #7cafc2">Updated 3/06/2026.</span>

## What is Node.js?

Node.js is a JavaScript runtime built on Chrome's V8 engine. It provides server-side execution of JavaScript with native file system access and a large package ecosystem.

## Prerequisites

* **Node.js (version 16 or higher)**
* **npm (version 7 or higher)**
* A **code editor** (VS Code recommended)
* Basic knowledge of **JavaScript and Node.js**

## Working Example

### Step 1 — Create a Project

```auto
mkdir dspdf-node-demo
cd dspdf-node-demo
npm init -y
```

### Step 2 — Install DsPdfJS

```auto
npm install @mescius/ds-pdf
```

### Step 3 — Create `node-pdf-example.mjs`

```javascript
// node-pdf-example.mjs
// Example: Generate a PDF file in Node.js using @mescius/ds-pdf (ESM + npm)

import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";

// Import required DsPdfJS APIs
import { connectDsPdf, DsPdfConfig, ObjectManager, PdfDocument } from "@mescius/ds-pdf";

// Resolve the current file and directory (ESM replacement for __dirname)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Configure the absolute path to the DsPdf.wasm file.
// In Node.js, you must explicitly provide the path to the WASM binary.
const wasmPath = path.resolve(
  __dirname,
  "node_modules/@mescius/ds-pdf/assets/DsPdf.wasm"
);
DsPdfConfig.wasmUrl = wasmPath;

// Main function that creates and saves a PDF document
async function createPdf() {
  console.log("🚀 Starting PDF generation in Node.js...");

  // Initialize the DsPdfJS runtime (loads and connects to the WASM module)
  const connected = await connectDsPdf();
  if (!connected) {
    throw new Error("Failed to initialize DsPdfJS.");
  }

  // Create an ObjectManager instance (required for managing PDF resources)
  const om = new ObjectManager();

  try {
    // Create a new PDF document
    const doc = new PdfDocument(om);

    // Create a new page context for drawing content
    const page = doc.newPageContext();

    // Draw text on the page at coordinates (x: 50, y: 50)
    page.drawText(
      {
        text: "Hello from Node.js!",
        fontSize: 18,
        foreColor: "DarkBlue"
      },
      50,
      50
    );

    // Save the PDF and obtain the binary data
    const pdfData = doc.savePdf();

    // Convert ArrayBuffer to a Node.js Buffer
    const buffer = Buffer.from(pdfData.buffer || pdfData);

    // Write the PDF file to disk
    fs.writeFileSync("node-example.pdf", buffer);

    console.log("✅ node-example.pdf created successfully!");
  } finally {
    // Always dispose ObjectManager to release WASM resources
    om.dispose();
  }
}

// Execute the PDF generation function
createPdf().catch(console.error);
```

### Step 4 — Run the Example

```auto
node node-pdf-example.mjs
```

### Expected Result

```auto
🚀 Starting PDF generation in Node.js...
✅ node-example.pdf created successfully!
```

A file `node-example.pdf` will be created in your current directory, with the text:

```plaintext
Hello from Node.js!
```

***

### Notes

* Uses ES modules (`import`) instead of CommonJS
* Native file system access via `fs`
* Stable and production-ready environment
* Recommended for server-side or automated PDF generation

***

### Project Structure

```auto
dspdf-node-demo/
├── node_modules/
├── package.json
├── package-lock.json
└── node-pdf-example.mjs
```