Node.js has undergone a remarkable transformation since its early days. If you've been writing Node.js for several years, you've likely witnessed this evolution firsthand---from the callback-heavy, CommonJS-dominated landscape to today's clean, standards-based development experience.
Node.js 自成立之初以来就经历了显着的转变。如果您已经编写 Node.js 好几年了,您可能亲眼目睹了这种演变------从回调密集、CommonJS 主导的环境到今天干净的、基于标准的开发体验。
The changes aren't just cosmetic; they represent a fundamental shift in how we approach server-side JavaScript development. Modern Node.js embraces web standards, reduces external dependencies, and provides a more intuitive developer experience. Let's explore these transformations and understand why they matter for your applications in 2025.
这些变化不仅仅是表面上的,更是表面上的。它们代表了我们处理服务器端 JavaScript 开发方式的根本转变。现代 Node.js 采用 Web 标准,减少外部依赖,并提供更直观的开发人员体验。让我们探讨这些转变,并了解为什么它们对 2025 年的应用程序很重要。
1. Module System: ESM is the New Standard 1、模块体系:ESM 是新标准
The module system is perhaps where you'll notice the biggest difference. CommonJS served us well, but ES Modules (ESM) have become the clear winner, offering better tooling support and alignment with web standards.
模块系统可能是您会注意到最大差异的地方。CommonJS 为我们提供了很好的服务,但 ES 模块 (ESM) 已成为明显的赢家,它提供了更好的工具支持并与 Web 标准保持一致。
The Old Way (CommonJS) 老路 (CommonJS)
Let's look at how we used to structure modules. This approach required explicit exports and synchronous imports:
让我们看看我们过去是如何构建模块的。这种方法需要显式导出和同步导入:
javascript
// math.js
function add(a, b) {
return a + b;
}
module.exports = { add };
// app.js
const { add } = require('./math');
console.log(add(2, 3));
Copy
This worked fine, but it had limitations---no static analysis, no tree-shaking, and it didn't align with browser standards.
这工作正常,但它有局限性------没有静态分析,没有摇树,而且它不符合浏览器标准。
The Modern Way (ES Modules with Node: Prefix) 现代方式(带有节点:前缀的 ES 模块)
Modern Node.js development embraces ES Modules with a crucial addition---the node:
prefix for built-in modules. This explicit naming prevents confusion and makes dependencies crystal clear:
现代 Node.js 开发采用了 ES 模块,并增加了一个关键的附加功能------内置模块的节点前
缀。这种显式命名可以防止混淆并使依赖关系非常清晰:
javascript
// math.js
export function add(a, b) {
return a + b;
}
// app.js
import { add } from './math.js';
import { readFile } from 'node:fs/promises'; // Modern node: prefix
import { createServer } from 'node:http';
console.log(add(2, 3));
Copy
The node:
prefix is more than just a convention---it's a clear signal to both developers and tools that you're importing Node.js built-ins rather than npm packages. This prevents potential conflicts and makes your code more explicit about its dependencies.
node:
前缀不仅仅是一个约定,它向开发人员和工具发出了一个明确的信号,表明你导入的是内置 Node.js 而不是 npm 包。这可以防止潜在的冲突,并使您的代码更明确地了解其依赖关系。
Top-Level Await: Simplifying Initialization 顶级等待:简化初始化
One of the most game-changing features is top-level await. No more wrapping your entire application in an async function just to use await at the module level:
最改变游戏规则的功能之一是顶级等待。不再需要将整个应用程序包装在异步函数中,只是为了在模块级别使用 await:
javascript
// app.js - Clean initialization without wrapper functions
import { readFile } from 'node:fs/promises';
const config = JSON.parse(await readFile('config.json', 'utf8'));
const server = createServer(/* ... */);
console.log('App started with config:', config.appName);
Copy
This eliminates the common pattern of immediately-invoked async function expressions (IIFE) that we used to see everywhere. Your code becomes more linear and easier to reason about.
这消除了我们过去随处可见的立即调用异步函数表达式 (IIFE) 的常见模式。您的代码变得更加线性,更容易推理。
2. Built-in Web APIs: Reducing External Dependencies 2. 内置 Web API:减少外部依赖
Node.js has embraced web standards in a big way, bringing APIs that web developers already know directly into the runtime. This means fewer dependencies and more consistency across environments.
Node.js 大力采用 Web 标准,将 Web 开发人员已经知道的 API 直接带入运行时。这意味着更少的依赖关系和更高的环境一致性。
Fetch API: No More HTTP Library Dependencies Fetch API:不再依赖 HTTP 库
Remember when every project needed axios, node-fetch, or similar libraries for HTTP requests? Those days are over. Node.js now includes the Fetch API natively:
还记得每个项目都需要 axios、node-fetch 或类似的库来处理 HTTP 请求吗?那些日子已经结束了。Node.js 现在原生包含 Fetch API:
rust
// Old way - external dependencies required
const axios = require('axios');
const response = await axios.get('https://api.example.com/data');
// Modern way - built-in fetch with enhanced features
const response = await fetch('https://api.example.com/data');
const data = await response.json();
Copy
But the modern approach goes beyond just replacing your HTTP library. You get sophisticated timeout and cancellation support built-in:
但现代方法不仅仅是替换您的 HTTP 库。您可以获得内置的复杂超时和取消支持:
javascript
async function fetchData(url) {
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(5000) // Built-in timeout support
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
return await response.json();
} catch (error) {
if (error.name === 'TimeoutError') {
throw new Error('Request timed out');
}
throw error;
}
}
Copy
This approach eliminates the need for timeout libraries and provides a consistent error handling experience. The AbortSignal.timeout()
method is particularly elegant---it creates a signal that automatically aborts after the specified time.
这种方法消除了对超时库的需求,并提供了一致的错误处理体验。AbortSignal.timeout()
方法特别优雅------它创建了一个在指定时间后自动中止的信号。
AbortController: Graceful Operation Cancellation AbortController:正常作取消
Modern applications need to handle cancellation gracefully, whether it's user-initiated or due to timeouts. AbortController provides a standardized way to cancel operations:
现代应用程序需要优雅地处理取消,无论是用户发起的还是由于超时。AbortController 提供了一种标准化的方法来取消作:
javascript
// Cancel long-running operations cleanly
const controller = new AbortController();
// Set up automatic cancellation
setTimeout(() => controller.abort(), 10000);
try {
const data = await fetch('https://slow-api.com/data', {
signal: controller.signal
});
console.log('Data received:', data);
} catch (error) {
if (error.name === 'AbortError') {
console.log('Request was cancelled - this is expected behavior');
} else {
console.error('Unexpected error:', error);
}
}
Copy
This pattern works across many Node.js APIs, not just fetch. You can use the same AbortController with file operations, database queries, and any async operation that supports cancellation.
此模式适用于许多 Node.js API,而不仅仅是 fetch。可以将相同的 AbortController 用于文件作、数据库查询和任何支持取消的异步作。
3. Built-in Testing: Professional Testing Without External Dependencies 3. 内置测试:专业测试,无外部依赖
Testing used to require choosing between Jest, Mocha, Ava, or other frameworks. Node.js now includes a full-featured test runner that covers most testing needs without any external dependencies.
过去,测试需要在 Jest、Mocha、Ava 或其他框架之间进行选择。Node.js 现在包括一个功能齐全的测试运行器,可以满足大多数测试需求,无需任何外部依赖项。
Modern Testing with Node.js Built-in Test Runner 使用内置测试运行程序进行现代测试 Node.js
The built-in test runner provides a clean, familiar API that feels modern and complete:
内置的测试运行程序提供了一个干净、熟悉的 API,感觉现代而完整:
javascript
// test/math.test.js
import { test, describe } from 'node:test';
import assert from 'node:assert';
import { add, multiply } from '../math.js';
describe('Math functions', () => {
test('adds numbers correctly', () => {
assert.strictEqual(add(2, 3), 5);
});
test('handles async operations', async () => {
const result = await multiply(2, 3);
assert.strictEqual(result, 6);
});
test('throws on invalid input', () => {
assert.throws(() => add('a', 'b'), /Invalid input/);
});
});
Copy
What makes this particularly powerful is how seamlessly it integrates with the Node.js development workflow:
它特别强大的是它与 Node.js 开发工作流程的无缝集成:
bash
# Run all tests with built-in runner
node --test
# Watch mode for development
node --test --watch
# Coverage reporting (Node.js 20+)
node --test --experimental-test-coverage
Copy
The watch mode is especially valuable during development---your tests re-run automatically as you modify code, providing immediate feedback without any additional configuration.
监视模式在开发过程中特别有价值 - 当您修改代码时,您的测试会自动重新运行,无需任何额外配置即可提供即时反馈。
4. Sophisticated Asynchronous Patterns 4. 复杂的异步模式
While async/await isn't new, the patterns around it have matured significantly. Modern Node.js development leverages these patterns more effectively and combines them with newer APIs.
虽然 async/await 并不新鲜,但它周围的模式已经非常成熟。现代 Node.js 开发更有效地利用这些模式,并将它们与较新的 API 相结合。
Async/Await with Enhanced Error Handling 具有增强错误处理功能的异步/等待
Modern error handling combines async/await with sophisticated error recovery and parallel execution patterns:
现代错误处理将 async/await 与复杂的错误恢复和并行执行模式相结合:
javascript
import { readFile, writeFile } from 'node:fs/promises';
async function processData() {
try {
// Parallel execution of independent operations
const [config, userData] = await Promise.all([
readFile('config.json', 'utf8'),
fetch('/api/user').then(r => r.json())
]);
const processed = processUserData(userData, JSON.parse(config));
await writeFile('output.json', JSON.stringify(processed, null, 2));
return processed;
} catch (error) {
// Structured error logging with context
console.error('Processing failed:', {
error: error.message,
stack: error.stack,
timestamp: new Date().toISOString()
});
throw error;
}
}
Copy
This pattern combines parallel execution for performance with comprehensive error handling. The Promise.all()
ensures that independent operations run concurrently, while the try/catch provides a single point for error handling with rich context.
此模式将并行执行的性能与全面的错误处理相结合。Promise.all()
确保独立作并发运行,而 try/catch 为具有丰富上下文的错误处理提供单点。
Modern Event Handling with AsyncIterators 使用 AsyncIterators 进行现代事件处理
Event-driven programming has evolved beyond simple event listeners. AsyncIterators provide a more powerful way to handle streams of events:
事件驱动的编程已经超越了简单的事件侦听器。AsyncIterators 提供了一种更强大的方法来处理事件流:
javascript
import { EventEmitter, once } from 'node:events';
class DataProcessor extends EventEmitter {
async *processStream() {
for (let i = 0; i < 10; i++) {
this.emit('data', `chunk-${i}`);
yield `processed-${i}`;
// Simulate async processing time
await new Promise(resolve => setTimeout(resolve, 100));
}
this.emit('end');
}
}
// Consume events as an async iterator
const processor = new DataProcessor();
for await (const result of processor.processStream()) {
console.log('Processed:', result);
}
Copy
This approach is particularly powerful because it combines the flexibility of events with the control flow of async iteration. You can process events in sequence, handle backpressure naturally, and break out of processing loops cleanly.
这种方法特别强大,因为它将事件的灵活性与异步迭代的控制流相结合。您可以按顺序处理事件,自然地处理背压,并干净地跳出处理循环。
5. Advanced Streams with Web Standards Integration 5. 具有 Web 标准集成的高级流
Streams remain one of Node.js's most powerful features, but they've evolved to embrace web standards and provide better interoperability.
流仍然是 Node.js 最强大的功能之一,但它们已经发展到拥抱 Web 标准并提供更好的互作性。
Modern Stream Processing 现代流处理
Stream processing has become more intuitive with better APIs and clearer patterns:
通过更好的 API 和更清晰的模式,流处理变得更加直观:
javascript
import { Readable, Transform } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
// Create transform streams with clean, focused logic
const upperCaseTransform = new Transform({
objectMode: true,
transform(chunk, encoding, callback) {
this.push(chunk.toString().toUpperCase());
callback();
}
});
// Process files with robust error handling
async function processFile(inputFile, outputFile) {
try {
await pipeline(
createReadStream(inputFile),
upperCaseTransform,
createWriteStream(outputFile)
);
console.log('File processed successfully');
} catch (error) {
console.error('Pipeline failed:', error);
throw error;
}
}
Copy
The pipeline
function with promises provides automatic cleanup and error handling, eliminating many of the traditional pain points with stream processing.
带有 promise 的管道
功能提供自动清理和错误处理,消除了流处理的许多传统痛点。
Web Streams Interoperability Web 流互作性
Modern Node.js can seamlessly work with Web Streams, enabling better compatibility with browser code and edge runtime environments:
新式 Node.js 可以与 Web 流无缝协作,从而更好地兼容浏览器代码和边缘运行时环境:
ini
// Create a Web Stream (compatible with browsers)
const webReadable = new ReadableStream({
start(controller) {
controller.enqueue('Hello ');
controller.enqueue('World!');
controller.close();
}
});
// Convert between Web Streams and Node.js streams
const nodeStream = Readable.fromWeb(webReadable);
const backToWeb = Readable.toWeb(nodeStream);
Copy
This interoperability is crucial for applications that need to run in multiple environments or share code between server and client.
这种互作性对于需要在多个环境中运行或在服务器和客户端之间共享代码的应用程序至关重要。
6. Worker Threads: True Parallelism for CPU-Intensive Tasks 6. 工作线程:CPU 密集型任务的真正并行性
JavaScript's single-threaded nature isn't always ideal for CPU-intensive work. Worker threads provide a way to leverage multiple cores effectively while maintaining the simplicity of JavaScript.
JavaScript 的单线程特性并不总是适合 CPU 密集型工作。工作线程提供了一种有效利用多核的方法,同时保持 JavaScript 的简单性。
Background Processing Without Blocking 无阻塞的后台处理
Worker threads are perfect for computationally expensive tasks that would otherwise block the main event loop:
工作线程非常适合计算成本高昂的任务,否则会阻塞主事件循环:
javascript
// worker.js - Isolated computation environment
import { parentPort, workerData } from 'node:worker_threads';
function fibonacci(n) {
if (n < 2) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
const result = fibonacci(workerData.number);
parentPort.postMessage(result);
Copy
The main application can delegate heavy computations without blocking other operations:
主应用程序可以委托繁重的计算,而不会阻塞其他作:
typescript
// main.js - Non-blocking delegation
import { Worker } from 'node:worker_threads';
import { fileURLToPath } from 'node:url';
async function calculateFibonacci(number) {
return new Promise((resolve, reject) => {
const worker = new Worker(
fileURLToPath(new URL('./worker.js', import.meta.url)),
{ workerData: { number } }
);
worker.on('message', resolve);
worker.on('error', reject);
worker.on('exit', (code) => {
if (code !== 0) {
reject(new Error(`Worker stopped with exit code ${code}`));
}
});
});
}
// Your main application remains responsive
console.log('Starting calculation...');
const result = await calculateFibonacci(40);
console.log('Fibonacci result:', result);
console.log('Application remained responsive throughout!');
Copy
This pattern allows your application to utilize multiple CPU cores while keeping the familiar async/await programming model.
此模式允许应用程序使用多个 CPU 内核,同时保持熟悉的异步/等待编程模型。
7. Enhanced Development Experience 7. 增强的开发体验
Modern Node.js prioritizes developer experience with built-in tools that previously required external packages or complex configurations.
现代 Node.js 优先考虑开发人员使用以前需要外部包或复杂配置的内置工具的体验。
Watch Mode and Environment Management 监视模式和环境管理
Development workflow has been significantly streamlined with built-in watch mode and environment file support:
通过内置的监视模式和环境文件支持,开发工作流程得到了显着简化:
rust
{
"name": "modern-node-app",
"type": "module",
"engines": {
"node": ">=20.0.0"
},
"scripts": {
"dev": "node --watch --env-file=.env app.js",
"test": "node --test --watch",
"start": "node app.js"
}
}
Copy
The --watch
flag eliminates the need for nodemon, while --env-file
removes the dependency on dotenv. Your development environment becomes simpler and faster:
--watch
标志消除了对 nodemon 的需求,而 --env-file
消除了对 dotenv 的依赖。您的开发环境变得更简单、更快捷:
arduino
// .env file automatically loaded with --env-file
// DATABASE_URL=postgres://localhost:5432/mydb
// API_KEY=secret123
// app.js - Environment variables available immediately
console.log('Connecting to:', process.env.DATABASE_URL);
console.log('API Key loaded:', process.env.API_KEY ? 'Yes' : 'No');
Copy
These features make development more pleasant by reducing configuration overhead and eliminating restart cycles.
这些功能通过减少配置开销和消除重启周期,使开发更加愉快。
8. Modern Security and Performance Monitoring 8. 现代安全和性能监控
Security and performance have become first-class concerns with built-in tools for monitoring and controlling application behavior.
安全性和性能已成为用于监视和控制应用程序行为的内置工具的首要问题。
Permission Model for Enhanced Security 增强安全性的权限模型
The experimental permission model allows you to restrict what your application can access, following the principle of least privilege:
实验性权限模型允许您按照最小权限原则限制应用程序可以访问的内容:
ini
# Run with restricted file system access
node --experimental-permission --allow-fs-read=./data --allow-fs-write=./logs app.js
# Network restrictions
node --experimental-permission --allow-net=api.example.com app.js
# Above allow-net feature not avaiable yet, PR merged in node.js repo, will be available in future release
Copy
This is particularly valuable for applications that process untrusted code or need to demonstrate security compliance.
这对于处理不受信任的代码或需要证明安全合规性的应用程序特别有价值。
Built-in Performance Monitoring 内置性能监控
Performance monitoring is now built into the platform, eliminating the need for external APM tools for basic monitoring:
性能监控现在内置于平台中,无需外部 APM 工具进行基本监控:
javascript
import { PerformanceObserver, performance } from 'node:perf_hooks';
// Set up automatic performance monitoring
const obs = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (entry.duration > 100) { // Log slow operations
console.log(`Slow operation detected: ${entry.name} took ${entry.duration}ms`);
}
}
});
obs.observe({ entryTypes: ['function', 'http', 'dns'] });
// Instrument your own operations
async function processLargeDataset(data) {
performance.mark('processing-start');
const result = await heavyProcessing(data);
performance.mark('processing-end');
performance.measure('data-processing', 'processing-start', 'processing-end');
return result;
}
Copy
This provides visibility into application performance without external dependencies, helping you identify bottlenecks early in development.
这提供了对应用程序性能的可见性,而无需外部依赖项,帮助您在开发早期识别瓶颈。
9. Application Distribution and Deployment 9. 应用程序分发和部署
Modern Node.js makes application distribution simpler with features like single executable applications and improved packaging.
现代 Node.js 通过单个可执行应用程序和改进的打包等功能使应用程序分发更简单。
Single Executable Applications 单个可执行应用程序
You can now bundle your Node.js application into a single executable file, simplifying deployment and distribution:
现在,您可以将 Node.js 应用程序捆绑到单个可执行文件中,从而简化部署和分发:
sql
# Create a self-contained executable
node --experimental-sea-config sea-config.json
Copy
The configuration file defines how your application gets bundled:
配置文件定义了应用程序的捆绑方式:
rust
{
"main": "app.js",
"output": "my-app-bundle.blob",
"disableExperimentalSEAWarning": true
}
Copy
This is particularly valuable for CLI tools, desktop applications, or any scenario where you want to distribute your application without requiring users to install Node.js separately.
这对于 CLI 工具、桌面应用程序或任何想要分发应用程序而无需用户单独安装应用程序 Node.js 场景特别有价值。
10. Modern Error Handling and Diagnostics 10. 现代错误处理和诊断
Error handling has evolved beyond simple try/catch blocks to include structured error handling and comprehensive diagnostics.
错误处理已经超越了简单的 try/catch 块,包括结构化错误处理和全面的诊断。
Structured Error Handling 结构化错误处理
Modern applications benefit from structured, contextual error handling that provides better debugging information:
新式应用程序受益于结构化的上下文错误处理,这些错误处理提供了更好的调试信息:
kotlin
class AppError extends Error {
constructor(message, code, statusCode = 500, context = {}) {
super(message);
this.name = 'AppError';
this.code = code;
this.statusCode = statusCode;
this.context = context;
this.timestamp = new Date().toISOString();
}
toJSON() {
return {
name: this.name,
message: this.message,
code: this.code,
statusCode: this.statusCode,
context: this.context,
timestamp: this.timestamp,
stack: this.stack
};
}
}
// Usage with rich context
throw new AppError(
'Database connection failed',
'DB_CONNECTION_ERROR',
503,
{ host: 'localhost', port: 5432, retryAttempt: 3 }
);
Copy
This approach provides much richer error information for debugging and monitoring, while maintaining a consistent error interface across your application.
此方法为调试和监视提供了更丰富的错误信息,同时在整个应用程序中保持一致的错误接口。
Advanced Diagnostics 高级诊断
Node.js includes sophisticated diagnostic capabilities that help you understand what's happening inside your application:
Node.js 包括复杂的诊断功能,可帮助您了解应用程序内部发生的情况:
php
import diagnostics_channel from 'node:diagnostics_channel';
// Create custom diagnostic channels
const dbChannel = diagnostics_channel.channel('app:database');
const httpChannel = diagnostics_channel.channel('app:http');
// Subscribe to diagnostic events
dbChannel.subscribe((message) => {
console.log('Database operation:', {
operation: message.operation,
duration: message.duration,
query: message.query
});
});
// Publish diagnostic information
async function queryDatabase(sql, params) {
const start = performance.now();
try {
const result = await db.query(sql, params);
dbChannel.publish({
operation: 'query',
sql,
params,
duration: performance.now() - start,
success: true
});
return result;
} catch (error) {
dbChannel.publish({
operation: 'query',
sql,
params,
duration: performance.now() - start,
success: false,
error: error.message
});
throw error;
}
}
Copy
This diagnostic information can be consumed by monitoring tools, logged for analysis, or used to trigger automatic remediation actions.
此诊断信息可由监视工具使用、记录以供分析或用于触发自动修正作。
11. Modern Package Management and Module Resolution 11. 现代包管理和模块解析
Package management and module resolution have become more sophisticated, with better support for monorepos, internal packages, and flexible module resolution.
包管理和模块解析变得更加复杂,更好地支持单存储库、内部包和灵活的模块解析。
Import Maps and Internal Package Resolution 导入映射和内部包解析
Modern Node.js supports import maps, allowing you to create clean internal module references:
Modern Node.js 支持导入映射,允许您创建干净的内部模块引用:
rust
{
"imports": {
"#config": "./src/config/index.js",
"#utils/*": "./src/utils/*.js",
"#db": "./src/database/connection.js"
}
}
Copy
This creates a clean, stable interface for internal modules:
这为内部模块创建了一个干净、稳定的界面:
javascript
// Clean internal imports that don't break when you reorganize
import config from '#config';
import { logger, validator } from '#utils/common';
import db from '#db';
Copy
These internal imports make refactoring easier and provide a clear distinction between internal and external dependencies.
这些内部导入使重构变得更加容易,并明确区分了内部和外部依赖关系。
Dynamic Imports for Flexible Loading 动态导入,灵活加载
Dynamic imports enable sophisticated loading patterns, including conditional loading and code splitting:
动态导入支持复杂的加载模式,包括条件加载和代码拆分:
javascript
// Load features based on configuration or environment
async function loadDatabaseAdapter() {
const dbType = process.env.DATABASE_TYPE || 'sqlite';
try {
const adapter = await import(`#db/adapters/${dbType}`);
return adapter.default;
} catch (error) {
console.warn(`Database adapter ${dbType} not available, falling back to sqlite`);
const fallback = await import('#db/adapters/sqlite');
return fallback.default;
}
}
// Conditional feature loading
async function loadOptionalFeatures() {
const features = [];
if (process.env.ENABLE_ANALYTICS === 'true') {
const analytics = await import('#features/analytics');
features.push(analytics.default);
}
if (process.env.ENABLE_MONITORING === 'true') {
const monitoring = await import('#features/monitoring');
features.push(monitoring.default);
}
return features;
}
Copy
This pattern allows you to build applications that adapt to their environment and only load the code they actually need.
此模式允许您构建适应其环境的应用程序,并且仅加载它们实际需要的代码。
The Path Forward: Key Takeaways for Modern Node.js (2025) 前进之路:现代 Node.js 的关键要点(2025 年)
As we look at the current state of Node.js development, several key principles emerge:
当我们审视 Node.js 发展的现状时,出现了几个关键原则:
- Embrace Web Standards : Use
node:
prefixes, fetch API, AbortController, and Web Streams for better compatibility and reduced dependencies
采用 Web 标准 :使用node:
前缀、获取 API、AbortController 和 Web Streams 以获得更好的兼容性并减少依赖性 - Leverage Built-in Tools : The test runner, watch mode, and environment file support reduce external dependencies and configuration complexity
利用内置工具 :测试运行程序、监视模式和环境文件支持可减少外部依赖项和配置复杂性 - Think in Modern Async Patterns : Top-level await, structured error handling, and async iterators make code more readable and maintainable
从现代异步模式中思考 :顶级等待、结构化错误处理和异步迭代器使代码更具可读性和可维护性 - Use Worker Threads Strategically : For CPU-intensive tasks, worker threads provide true parallelism without blocking the main thread
有策略地使用工作线程 :对于 CPU 密集型任务,工作线程提供真正的并行性,而不会阻塞主线程 - Adopt Progressive Enhancement : Use permission models, diagnostics channels, and performance monitoring to build robust, observable applications
采用渐进式增强 :使用权限模型、诊断通道和性能监控来构建健壮、可观察的应用程序 - Optimize for Developer Experience : Watch mode, built-in testing, and import maps create a more pleasant development workflow
针对开发人员体验进行优化 :监视模式、内置测试和导入映射创建了更愉快的开发工作流程 - Plan for Distribution : Single executable applications and modern packaging make deployment simpler
分发计划 :单个可执行应用程序和现代打包使部署更简单
The transformation of Node.js from a simple JavaScript runtime to a comprehensive development platform is remarkable. By adopting these modern patterns, you're not just writing contemporary code---you're building applications that are more maintainable, performant, and aligned with the broader JavaScript ecosystem.
Node.js 从简单的 JavaScript 运行时到综合开发平台的转变是了不起的。通过采用这些现代模式,您不仅在编写现代代码,还可以构建更易于维护、性能更高且与更广泛的 JavaScript 生态系统保持一致的应用程序。
The beauty of modern Node.js lies in its evolution while maintaining backward compatibility. You can adopt these patterns incrementally, and they work alongside existing code. Whether you're starting a new project or modernizing an existing one, these patterns provide a clear path toward more robust, enjoyable Node.js development.
现代 Node.js 的美妙之处在于它在保持向后兼容性的同时不断演变。可以逐步采用这些模式,它们与现有代码一起工作。无论您是开始一个新项目还是对现有项目进行现代化改造,这些模式都为更强大、更愉快的 Node.js 开发提供了一条清晰的道路。
As we move through 2025, Node.js continues to evolve, but the foundational patterns we've explored here provide a solid base for building applications that will remain modern and maintainable for years to come.
随着我们进入 2025 年,Node.js 将继续发展,但我们在这里探索的基本模式为构建应用程序提供了坚实的基础,这些应用程序将在未来几年保持现代和可维护。