> For AI agents: the complete documentation index is available at /next/llms.txt, the full documentation bundle is available at /next/llms-full.txt.

# Node.js Native Modules

Lynxtron's support for Node.js native modules is aligned with Electron's: both can use npm native modules in the Node.js environment that runs with the app, and both can load `.node` binary artifacts from those modules.

The main difference is the rebuild target. In Electron, people usually use `@electron/rebuild` to rebuild native modules for the Electron runtime. In Lynxtron, use `@lynx-js/lynxtron-rebuild` to rebuild native modules for the Lynxtron runtime.

| Capability                  | Electron                            | Lynxtron                                                                             |
| --------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------ |
| Use npm native modules      | Supported, such as `better-sqlite3` | Supported, such as `better-sqlite3`                                                  |
| Rebuild for the app runtime | `@electron/rebuild`                 | [`@lynx-js/lynxtron-rebuild`](/next/lynxtron/api/@lynx-js/lynxtron-rebuild/index.md) |

## What is a Node.js native module?

A Node.js native module is an npm package that contains not only JavaScript code, but also locally compiled artifacts, usually `.node` files. They are commonly implemented in C/C++ and exposed to JavaScript through Node-API or node-gyp, and are suitable for scenarios such as:

- high-performance capabilities provided by C/C++ extensions
- npm packages that depend on `.node` binary artifacts
- local system capabilities that are only accessible in the Node.js environment

Native modules must be compatible with the target Lynxtron runtime, operating system, and architecture. **Modules that depend on the Node.js/V8 ABI need a matching build.** Modules using only Node-API may reuse a compatible prebuilt binary when the runtime supports its Node-API version and its native dependencies are available; not every `.node` file requires recompilation.

If a module was compiled only for your regular local Node.js environment, you may run into ABI mismatch errors when loading it in Lynxtron. A typical error looks like this:

```bash
Error: The module '/path/to/native/module.node'
was compiled against a different Node.js version using
NODE_MODULE_VERSION XXX. This version of Node.js requires
NODE_MODULE_VERSION YYY. Please try re-compiling or re-installing
the module.
```

In Electron, people usually solve this with `@electron/rebuild`. In Lynxtron, **use `@lynx-js/lynxtron-rebuild` instead**.

## Rebuild and Require Native Modules

When using an npm native module in Lynxtron, install the module and run `@lynx-js/lynxtron-rebuild` first, then import or require the module in the Node.js environment.

Install the npm native module you need, and install `@lynx-js/lynxtron-rebuild`:

```bash
npm install <native-module>
```


```sh [npm]
npm install -D @lynx-js/lynxtron-rebuild
```

```sh [yarn]
yarn add -D @lynx-js/lynxtron-rebuild
```

```sh [pnpm]
pnpm add -D @lynx-js/lynxtron-rebuild
```

```sh [bun]
bun add -D @lynx-js/lynxtron-rebuild
```

```sh [deno]
deno add -D npm:@lynx-js/lynxtron-rebuild
```

Then run `@lynx-js/lynxtron-rebuild` to rebuild native modules for Lynxtron:

```bash
npx @lynx-js/lynxtron-rebuild
```

The tool may reuse a compatible Node-API prebuild instead of compiling from source. A successful exit or “Successfully rebuilt” message alone does not prove that a new binary was compiled. Check the build log and the actual loaded `.node` path, then exercise the module inside Lynxtron and the packaged app, not only in your system Node.js.

Import the native module in the app's Node.js environment:

```typescript
import nativeModule from 'native-module';

// Or use CommonJS:
const nativeModule = require('native-module');
```

If you need to expose Node.js capabilities to Lynx UI, use bridge messaging or [preload scripts](/next/lynxtron/learn/Communication-Between-Node-And-Lynx.md#use-preload-scripts) as described in [Communication Between Node.js and Lynx](/next/lynxtron/learn/Communication-Between-Node-And-Lynx.md).

## Example: Todo List Application

:::info Before you start

✅ You have already completed [Getting Started with Lynxtron](/next/lynxtron/introduction.md)

✅ Your machine already has the local build toolchain required by `node-gyp`, such as Python, C/C++ Build Tools, or Xcode Command Line Tools

:::


**This is an example below: todolist**

**Bundle:** `dist/desktop/main.lynx.bundle`

```tsx
import { useCallback, useEffect, useMemo, useState } from '@lynx-js/react';
import '@lynxtron-examples/config/tokens.css';
import './App.css';

interface Todo {
  id: number;
  title: string;
  completed: boolean;
  createdAt: number;
}

type Filter = 'all' | 'active' | 'completed';

const inputValueProp = (value: string) => ({ value }) as any;
const readInputValue = (e: any): string => e?.detail?.value ?? e?.value ?? '';

function bridge<T>(name: string, data: any = {}): Promise<T> {
  return new Promise((resolve, reject) => {
    try {
      (NativeModules as any).bridge.call(name, data, (res: any) => {
        if (res && typeof res === 'object' && 'error' in res) reject(new Error(res.error));
        else resolve(res as T);
      });
    } catch (err) {
      reject(err);
    }
  });
}

export function App() {
  const [todos, setTodos] = useState<Todo[]>([]);
  const [input, setInput] = useState('');
  const [filter, setFilter] = useState<Filter>('all');
  const [storePath, setStorePath] = useState('');
  const [error, setError] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    try {
      setTodos(await bridge<Todo[]>('list'));
    } catch (err: any) {
      setError(err?.message ?? 'Failed to load todos');
    }
  }, []);

  useEffect(() => {
    bridge<string>('storePath').then(setStorePath).catch(() => {});
    refresh();
  }, [refresh]);

  const submit = useCallback(async () => {
    const title = input.trim();
    if (!title) return;
    try {
      setTodos(await bridge<Todo[]>('add', { title }));
      setInput('');
      setError(null);
    } catch (err: any) {
      setError(err?.message ?? 'Failed to add');
    }
  }, [input]);

  const toggle = useCallback(async (id: number) => {
    try {
      setTodos(await bridge<Todo[]>('toggle', { id }));
    } catch (err: any) {
      setError(err?.message ?? 'Failed to toggle');
    }
  }, []);

  const remove = useCallback(async (id: number) => {
    try {
      setTodos(await bridge<Todo[]>('remove', { id }));
    } catch (err: any) {
      setError(err?.message ?? 'Failed to remove');
    }
  }, []);

  const clearCompleted = useCallback(async () => {
    try {
      setTodos(await bridge<Todo[]>('clearCompleted'));
    } catch (err: any) {
      setError(err?.message ?? 'Failed to clear');
    }
  }, []);

  const visible = useMemo(() => {
    if (filter === 'active') return todos.filter((t) => !t.completed);
    if (filter === 'completed') return todos.filter((t) => t.completed);
    return todos;
  }, [todos, filter]);

  const remaining = todos.filter((t) => !t.completed).length;

  return (
    <view className="container">
      <view className="header">
        <text className="title">Todos</text>
        <text className="subtitle">{remaining} remaining</text>
      </view>

      <view className="input-row">
        <input
          className="input"
          placeholder="What needs to be done?"
          {...inputValueProp(input)}
          bindinput={(e: any) => setInput(readInputValue(e))}
          bindconfirm={submit}
        />
        <view className="add-button" bindtap={submit}>
          <text className="button-text">Add</text>
        </view>
      </view>

      <view className="filter-row">
        {(['all', 'active', 'completed'] as Filter[]).map((f) => (
          <view
            key={f}
            className={`filter-chip ${filter === f ? 'active' : ''}`}
            bindtap={() => setFilter(f)}
          >
            <text className="filter-text">{f.charAt(0).toUpperCase() + f.slice(1)}</text>
          </view>
        ))}
      </view>

      <scroll-view scroll-y className="todo-list">
        {visible.length === 0 && (
          <text className="empty">No {filter === 'all' ? '' : filter} todos yet.</text>
        )}
        {visible.map((t) => (
          <view key={t.id} className={`todo-item ${t.completed ? 'completed' : ''}`}>
            <view className="checkbox" bindtap={() => toggle(t.id)}>
              <text className="checkbox-mark">{t.completed ? '✓' : ''}</text>
            </view>
            <text className="todo-title" text-maxline="2">
              {t.title}
            </text>
            <view className="delete-button" bindtap={() => remove(t.id)}>
              <text className="delete-mark">×</text>
            </view>
          </view>
        ))}
      </scroll-view>

      <view className="footer">
        <text className="store-path" text-maxline="1">
          {storePath}
        </text>
        {todos.some((t) => t.completed) && (
          <view className="clear-button" bindtap={clearCompleted}>
            <text className="button-text">Clear completed</text>
          </view>
        )}
      </view>

      {error && <text className="error">{error}</text>}
    </view>
  );
}

```



This example uses `sqlite3` to build a **Todo List application**:

- **Node.js side**: persist to-do items in `todos.db` under the app's user data directory using the callback-based `sqlite3` API.
- **Lynx side**: call Node.js logic through communication APIs to add, list, toggle, and delete items.

The following excerpt shows the example's schema initialization. The full [Todo source](https://github.com/lynx-community/lynxtron-examples/blob/main/showcases/todolist/src/main/desktop/main.ts) also wraps `db.run` and `db.all` in Promises, waits for `dbReady` in bridge handlers, and converts `completed` to a boolean and `created_at` to `createdAt` when listing rows.

```typescript
// src/main/desktop/main.ts
import { app } from '@lynx-js/lynxtron';
import fs from 'node:fs';
import path from 'node:path';
import sqlite3 from 'sqlite3';

app.whenReady().then(() => {
  const dir = app.getPath('userData');
  fs.mkdirSync(dir, { recursive: true });
  const dbPath = path.join(dir, 'todos.db');
  const db = new sqlite3.Database(dbPath);
  db.serialize();

  const dbReady = new Promise<void>((resolve, reject) => {
    db.run(
      `CREATE TABLE IF NOT EXISTS todos (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT NOT NULL,
        completed INTEGER NOT NULL DEFAULT 0,
        created_at INTEGER NOT NULL
      )`,
      (err) => (err ? reject(err) : resolve()),
    );
  });

  // Register the showcase bridge handlers here; await dbReady before queries.
});
```

## Related docs

- [Communication Between Node.js And LynxView](/next/lynxtron/learn/Communication-Between-Node-And-Lynx.md)
- [`LynxWindow.sendGlobalEvent()`](/next/lynxtron/api/@lynx-js/lynxtron/Class.LynxWindow.md#sendglobalevent)
- [Lynx Native Libraries](/next/lynxtron/Native-Libraries/Lynx-Native-Libraries.md)

## Next steps

Once you are comfortable with Node.js native modules, you can try:

1. **Add more local capabilities**: for example, use `sharp` for thumbnail generation, or `node-pty` for an embedded terminal
2. **Combine with Lynx native libraries**: use Node.js native modules together with Lynx native libraries to build more complex desktop applications
