> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/zhcndoc/bun/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js Compatibility

> Bun implements most Node.js APIs for drop-in compatibility

Bun aims to be a drop-in replacement for Node.js. Most Node.js applications work with Bun with little to no changes. Bun implements the most commonly used Node.js built-in modules and APIs.

## Built-in Module Support

Bun implements the following Node.js built-in modules:

### Fully Supported

These modules are fully or nearly fully implemented:

<CardGroup cols={2}>
  <Card title="node:fs" icon="folder">
    File system operations (sync and async)
  </Card>

  <Card title="node:path" icon="route">
    File path manipulation
  </Card>

  <Card title="node:buffer" icon="memory">
    Binary data handling
  </Card>

  <Card title="node:stream" icon="water">
    Streaming data
  </Card>

  <Card title="node:crypto" icon="lock">
    Cryptographic operations
  </Card>

  <Card title="node:http" icon="globe">
    HTTP client and server
  </Card>

  <Card title="node:https" icon="shield">
    HTTPS client and server
  </Card>

  <Card title="node:net" icon="network-wired">
    TCP networking
  </Card>

  <Card title="node:url" icon="link">
    URL parsing and formatting
  </Card>

  <Card title="node:util" icon="wrench">
    Utility functions
  </Card>

  <Card title="node:events" icon="bolt">
    Event emitter
  </Card>

  <Card title="node:os" icon="computer">
    Operating system info
  </Card>
</CardGroup>

### Partially Supported

These modules have most features implemented:

* **node:child\_process** - Spawn processes (use `Bun.spawn()` for better performance)
* **node:dns** - DNS lookups
* **node:zlib** - Compression (use `Bun.gzipSync()` for better performance)
* **node:readline** - Command-line input
* **node:timers** - setTimeout, setInterval
* **node:assert** - Testing assertions
* **node:querystring** - Query string parsing
* **node:worker\_threads** - Multi-threading
* **node:perf\_hooks** - Performance monitoring

### Not Yet Implemented

These modules are planned but not yet available:

* **node:cluster** - Load balancing (use `Bun.serve()` with `reusePort`)
* **node:dgram** - UDP sockets (use native UDP in Bun)
* **node:vm** - Virtual machine
* **node:repl** - Interactive shell
* **node:tty** - Terminal control

## Import Syntax

Use the `node:` prefix to import Node.js modules:

```typescript theme={null}
import fs from "node:fs";
import { readFile } from "node:fs/promises";
import path from "node:path";
```

Bun also supports the legacy syntax without `node:`:

```typescript theme={null}
import fs from "fs";
import path from "path";
```

Both syntaxes work identically in Bun.

## fs Module

Bun fully implements the `node:fs` module:

```typescript theme={null}
import fs from "node:fs";
import { readFile, writeFile } from "node:fs/promises";

// Synchronous
const data = fs.readFileSync("file.txt", "utf-8");
fs.writeFileSync("output.txt", data);

// Promises
const content = await readFile("file.txt", "utf-8");
await writeFile("output.txt", content);

// Callbacks
fs.readFile("file.txt", "utf-8", (err, data) => {
  if (err) throw err;
  console.log(data);
});
```

<Tip>
  For better performance, use `Bun.file()` and `Bun.write()` instead of `fs` methods.
</Tip>

## http and https Modules

Create HTTP servers using Node.js APIs:

```typescript theme={null}
import http from "node:http";

const server = http.createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello from Node.js API");
});

server.listen(3000);
```

<Tip>
  For better performance, use `Bun.serve()` instead of the `http` module.
</Tip>

## Buffer

Bun implements the Node.js `Buffer` class:

```typescript theme={null}
const buf = Buffer.from("Hello");
console.log(buf.toString("hex"));  // 48656c6c6f

// Buffer methods
Buffer.alloc(10);
Buffer.concat([buf1, buf2]);
Buffer.compare(buf1, buf2);
```

## process

The global `process` object is available:

```typescript theme={null}
process.argv          // Command-line arguments
process.env           // Environment variables
process.cwd()         // Current working directory
process.exit(0)       // Exit process
process.platform      // OS platform
process.version       // Node.js version (emulated)
process.versions.bun  // Bun version

// Events
process.on("exit", (code) => {
  console.log(`Exiting with code ${code}`);
});

process.on("uncaughtException", (err) => {
  console.error("Uncaught exception:", err);
});
```

## \_\_dirname and \_\_filename

These globals are available in CommonJS modules:

```javascript theme={null}
console.log(__dirname);   // Directory path
console.log(__filename);  // File path
```

In ESM, use `import.meta`:

```typescript theme={null}
import.meta.dir    // Same as __dirname
import.meta.path   // Same as __filename
```

## require()

Bun supports `require()` for CommonJS modules:

```javascript theme={null}
const fs = require("node:fs");
const myModule = require("./my-module");
```

You can also use `require()` in ESM files for better compatibility:

```typescript theme={null}
// This works in Bun
import fs from "node:fs";
const path = require("node:path");
```

## Module Resolution

Bun follows Node.js module resolution rules:

1. Resolve `node_modules` directories
2. Check `package.json` `"exports"` field
3. Try file extensions: `.ts`, `.tsx`, `.js`, `.jsx`, `.json`
4. Try `index` files

Additional Bun features:

* Native TypeScript support (no need for ts-node)
* Automatic JSX transformation
* Import from `package.json` `"module"` field

## Package.json Compatibility

Bun reads standard `package.json` fields:

```json theme={null}
{
  "name": "my-package",
  "version": "1.0.0",
  "main": "./index.js",
  "module": "./index.mjs",
  "types": "./index.d.ts",
  "exports": {
    ".": {
      "import": "./index.mjs",
      "require": "./index.js"
    }
  },
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.18.0"
  }
}
```

Run scripts with `bun run`:

```bash theme={null}
bun run start  # Executes with Bun instead of Node.js
```

## Environment Variables

Access environment variables via `process.env`:

```typescript theme={null}
const apiKey = process.env.API_KEY;
process.env.NODE_ENV = "production";
```

Bun automatically loads `.env` files. See [Environment Variables](/runtime/environment-variables).

## npm Package Compatibility

Bun is compatible with most npm packages:

* ✅ Pure JavaScript packages work without changes
* ✅ Packages with native modules (Node-API/N-API) are supported
* ✅ TypeScript packages work natively
* ⚠️ Packages with node-gyp builds may need recompilation

## Performance Comparison

While Bun maintains Node.js compatibility, Bun's native APIs are often faster:

| Operation     | Node.js API             | Bun Native API      |
| ------------- | ----------------------- | ------------------- |
| Read file     | `fs.readFileSync()`     | `Bun.file().text()` |
| Write file    | `fs.writeFileSync()`    | `Bun.write()`       |
| HTTP server   | `http.createServer()`   | `Bun.serve()`       |
| Spawn process | `child_process.spawn()` | `Bun.spawn()`       |
| SQLite        | `better-sqlite3`        | `bun:sqlite`        |
| Hash          | `crypto.createHash()`   | `Bun.hash()`        |

<Tip>
  Use Bun's native APIs for better performance, but Node.js APIs for maximum compatibility.
</Tip>

## Migration Guide

To migrate a Node.js project to Bun:

<Steps>
  <Step title="Install Bun">
    ```bash theme={null}
    curl -fsSL https://bun.sh/install | bash
    ```
  </Step>

  <Step title="Install dependencies">
    ```bash theme={null}
    bun install
    ```

    This reads your `package.json` and installs dependencies.
  </Step>

  <Step title="Update scripts">
    Replace `node` with `bun` in your scripts:

    ```diff package.json theme={null}
    {
      "scripts": {
    -   "start": "node server.js",
    +   "start": "bun run server.js",
      }
    }
    ```
  </Step>

  <Step title="Test your application">
    ```bash theme={null}
    bun run start
    ```

    Most apps work without changes!
  </Step>

  <Step title="Optional: Use Bun APIs">
    For better performance, replace Node.js APIs with Bun equivalents:

    ```diff server.ts theme={null}
    - import fs from "node:fs";
    - const data = fs.readFileSync("file.txt", "utf-8");
    + const file = Bun.file("file.txt");
    + const data = await file.text();
    ```
  </Step>
</Steps>

## Known Differences

A few differences exist between Bun and Node.js:

1. **Bun is faster**: Startup time and runtime performance are significantly better
2. **Native TypeScript**: No need for `ts-node` or transpilation
3. **Top-level await**: Works everywhere, not just ES modules
4. **Different engine**: JavaScriptCore instead of V8 (rare compatibility issues)

## Check Compatibility

To check if a package works with Bun:

1. Check [Bun compatibility tracker](https://github.com/oven-sh/bun/issues?q=is%3Aissue+label%3Acompat)
2. Try installing and running tests: `bun install && bun test`
3. Report issues at [github.com/oven-sh/bun](https://github.com/oven-sh/bun)

## Next Steps

<CardGroup cols={2}>
  <Card title="Bun APIs" icon="bolt" href="/runtime/bun-apis">
    Learn about Bun-specific APIs
  </Card>

  <Card title="Package Manager" icon="box" href="/cli/install">
    Use Bun's fast package manager
  </Card>

  <Card title="Web APIs" icon="globe" href="/runtime/web-apis">
    Web standard APIs in Bun
  </Card>

  <Card title="Quickstart" icon="rocket" href="/quickstart">
    Build your first Bun app
  </Card>
</CardGroup>
