菜单

Node.js API Polyfill

相关源文件

This page documents the implementation of Node.js built-in module polyfills in Deno. The deno_node extension provides JavaScript and Rust implementations that emulate Node.js APIs, enabling Node.js code to run in Deno with minimal modifications.

For more information about npm integration, see NPM Integration.

概述

The Node.js compatibility layer is implemented through the deno_node extension, which registers over 200 operations and provides polyfills for all major Node.js built-in modules. The extension combines JavaScript polyfills with Rust-based operations to provide faithful Node.js API compatibility.

扩展架构

来源

实现架构

The deno_node extension implements Node.js compatibility through a structured layered approach

Core Extension Structure

Module Resolution System

来源

Core Polyfilled Modules

HTTP/HTTPS Implementation

The HTTP polyfills provide Node.js-compatible APIs built on Deno's native HTTP capabilities. The implementation includes dedicated Rust operations and JavaScript wrappers.

ClientRequest Implementation

关键操作

操作目的
op_node_http_request_with_connInitiates HTTP request with connection
op_node_http_await_responseAwaits HTTP response
op_node_http_await_informationHandles informational responses (1xx)
op_node_http_fetch_response_upgradeHandles protocol upgrades

来源

Global Process Object

The process global is implemented through a combination of JavaScript polyfills and native operations, providing Node.js-compatible process information and control.

Process Object Structure

来源

Network (Net) Module

The net module provides TCP networking functionality through a combination of LibuvStreamWrap and connection management classes.

Socket Implementation

来源

Cryptography Module

The crypto module provides cryptographic functionality through a comprehensive set of Rust operations combined with JavaScript wrappers.

Crypto Operations Mapping

Key Crypto Operations

Operation Family示例
哈希op_node_create_hash, op_node_hash_update, op_node_hash_digest
Symmetric Cryptoop_node_create_cipheriv, op_node_cipheriv_encrypt
Random Generationop_node_fill_random, op_node_random_int
Key Derivationop_node_pbkdf2, op_node_hkdf, op_node_scrypt
Asymmetric Cryptoop_node_generate_rsa_key, op_node_sign, op_node_verify

File System Module

The fs module provides file system operations through dedicated Node.js operations that wrap Deno's file system APIs.

FS Operations

Node.js FunctionRust Operation目的
fs.exists()op_node_fs_existsCheck file/directory existence
fs.cp()op_node_cpCopy files/directories
fs.lchown()op_node_lchownChange file ownership
fs.lutimes()op_node_lutimesChange file timestamps
fs.statfs()op_node_statfsGet filesystem statistics

DNS Module

DNS resolution is provided through the cares_wrap internal binding and dedicated DNS operations.

DNS Resolution Flow

来源

实现模式

The Node.js polyfills use several distinct implementation strategies based on complexity and system requirements

1. Pure JavaScript Polyfills

Simple APIs implemented entirely in JavaScript using existing Deno APIs

示例

  • util.promisify() - Pure JavaScript utility
  • Event emitter patterns
  • Stream transformations
  • Simple HTTP header manipulation

2. Hybrid JavaScript + Ops

Complex APIs requiring both JavaScript logic and native operations

示例

  • http.ClientRequest - Uses op_node_http_request_with_conn
  • crypto.createHash() - Uses op_node_create_hash
  • fs.exists() - Uses op_node_fs_exists

3. Global Object Proxying

Node.js-specific globals are provided through V8 property handlers

Global Handler Implementation

Managed Globals

  • Buffer (Node.js only)
  • clearImmediate, setImmediate (Node.js only)
  • global (Node.js only)
  • process (conditional availability)
  • window (Deno only)

4. Module Resolution Strategy

The require system implements Node.js module resolution through specialized operations

Module Loading Flow

关键操作

  • op_require_resolve_lookup_paths - Resolves module lookup paths
  • op_require_read_package_scope - Reads package.json files
  • op_require_stat - File system stat operations
  • op_require_real_path - Resolves real file paths

来源

Polyfill Coverage and Status

Built-in Module Support

The deno_node extension provides polyfills for all major Node.js built-in modules

Core Modules Coverage

模块状态关键组件
http✅ CompleteClientRequest, IncomingMessage, ServerResponse, Server
https✅ CompleteAgent, Server, request(), get()
net✅ CompleteSocket, Server, createConnection()
fs✅ CompleteAll sync/async methods, fs.promises
crypto✅ CompleteHashing, ciphers, key generation, certificates
✅ CompleteReadable, Writable, Duplex, Transform
dns✅ Completelookup(), resolve*(), promises API
url✅ CompleteURL, URLSearchParams
buffer✅ CompleteBuffer 类及其所有方法
process✅ Complete全局 process 对象
path✅ Complete路径操作工具
os✅ Complete系统信息 API
util✅ Complete实用函数,包括 promisify
events✅ CompleteEventEmitter
assert✅ Complete断言测试
querystring✅ CompleteURL 查询字符串实用工具
timers✅ CompletesetTimeout, setInterval, setImmediate
child_process✅ Complete进程生成和控制
cluster⚠️ 部分支持基本集群支持
worker_threads⚠️ 部分支持工作线程实现
v8⚠️ 部分支持V8 引擎实用工具
vm✅ Complete脚本执行上下文

Node.js 兼容性级别

基于广泛的测试套件,Deno 在大多数 Node.js API 上实现了高度兼容性。

测试覆盖率统计

领域兼容性测试文件
HTTP/HTTPS~95%http_test.ts, https_test.ts
网络~90%net_test.ts, tls_test.ts
文件系统~95%多个 fs_*_test.ts 文件
进程管理~85%process_test.ts
Crypto~90%crypto_test.ts
~95%stream_test.ts

来源

高级实现细节

TLS/SSL 实现

TLS 功能通过 _tls_wrap 模块提供,该模块使用 Deno 的原生 TLS 功能实现了 Node.js 的 TLS API。

TLS 套接字架构

关键 TLS 操作

  • startTlsInternal() - 启动 TLS 握手
  • op_tls_start() - 原生 TLS 连接建立
  • op_tls_key_static() - TLS 密钥对创建

VM 上下文实现

vm 模块通过 V8 的上下文 API 在隔离的上下文中提供脚本执行。

VM 操作流程

内部绑定系统

Node.js 的内部模块通过 internal_binding 系统暴露。

绑定模块结构

来源

测试与验证

Deno 的 Node.js 兼容层经过广泛测试,以确保功能正常。

  1. 单个模块的单元测试
  2. 使用 Node.js 测试套件的兼容性测试
  3. 与真实 npm 包的集成测试

对 Node.js 的兼容性正在持续衡量和改进,重点在于支持最广泛使用的模块和 API。

来源

  • tests/unit_node/http_test.ts
  • tests/unit_node/process_test.ts
  • tests/node_compat/config.jsonc
  • tests/node_compat/runner/TODO.md

结论

Deno 的 Node.js API polyfills 提供了与 Node.js 相当的兼容性,允许开发者在 Deno 中运行大多数 Node.js 代码,只需进行少量更改。该实现战略性地平衡了忠实还原 API 和利用 Deno 的原生功能来提高安全性和性能。

虽然某些高级或不太常用的 Node.js 功能可能存在限制,但对流行 Node.js 模块的核心功能提供了良好的支持,使得 Deno 成为运行和逐步迁移 Node.js 应用程序的可行平台。