JavaScript/TypeScript Setup

Installation

Install the DON parser package using npm:

npm add donly

You can also use other package managers like yarn or pnpm:

yarn add donly
pnpm add donly

Basic Usage

Import the DON parser and use it to parse DON text:

import { DON } from "donly";

const text = `
name "my-application"
version "1.0.0"
port 8080
enabled true
`;

const directives = DON.parse(text);

console.log(directives);

The DON.parse() method returns an array of directives that you can iterate through.

Understanding Directives

Each directive has three main properties:

Accessing Directive Properties

import { DON } from "donly";

const text = `
name "my-app"
port 8080
`;

const directives = DON.parse(text);

// Iterate through directives
directives.forEach((directive) => {
  console.log("Name:", directive.name);
  console.log("Arguments:", directive.args);
  console.log("Has children:", directive.children.length > 0);
});

Working with Nested Directives

You can access sub-directives through the children property:

import { DON } from "donly";

const configText = `
server {
  host "localhost"
  port 3000
  
  route /api/* {
    handler "apiHandler"
    timeout 30
  }
}
`;

const directives = DON.parse(configText);

// Get the server directive
const serverDirective = directives.find((d) => d.name === "server");

// Iterate through server's children (sub-directives)
serverDirective.children.forEach((child) => {
  console.log(`${child.name}:`, child.args);

  // Access nested children if they exist
  if (child.children.length > 0) {
    console.log("  Sub-directives:");
    child.children.forEach((subChild) => {
      console.log(`    ${subChild.name}:`, subChild.args);
    });
  }
});

Complete Example

Here’s a complete example showing how to parse and work with DON data:

import { DON } from "donly";

const configText = `
name "my-server"
version "2.0.0"
port 3000

server {
  host "localhost"
  ssl true
  
  route /api/* {
    handler "apiHandler"
    timeout 30
  }
}
`;

// Parse the configuration
const directives = DON.parse(configText);

// Access directive values
const nameDirective = directives.find((d) => d.name === "name");
console.log("App name:", nameDirective.args[0]);
// Output: App name: my-server

const portDirective = directives.find((d) => d.name === "port");
console.log("Port:", portDirective.args[0]);
// Output: Port: 3000

// Access nested directives
const serverDirective = directives.find((d) => d.name === "server");
console.log("Server has", serverDirective.children.length, "sub-directives");

// Iterate through server's children
serverDirective.children.forEach((child) => {
  console.log(`- ${child.name}:`, child.args);
});
// Output:
// - host: ["localhost"]
// - ssl: [true]
// - route: ["/api/*"]

TypeScript Support

The donly package includes full TypeScript type definitions out of the box. No additional installation required.

Next Steps