Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,它让开发者能够使用 JavaScript 编写服务器端应用程序。本章将带你了解 Node.js 的基本概念、特点以及如何快速上手。
Node.js 是一个开源、跨平台的 JavaScript 运行环境,它允许在服务器端执行 JavaScript 代码。Node.js 基于 Google 的 V8 引擎(该引擎用于 Chrome 浏览器),并对其进行了优化,使其在服务器端表现出色。Node.js 使用事件驱动、非阻塞 I/O 模型,使其轻量且高效,特别适合数据密集型的实时应用。
Node.js 的包管理器 npm 是全球最大的开源库生态系统,提供了丰富的模块供开发者使用。
worker_threads 模块创建多线程来处理 CPU 密集型任务。
要开始使用 Node.js,首先需要在你的计算机上安装它。以下是安装步骤:
node -v
npm -v
如果看到版本号输出,说明安装成功。
让我们从一个经典的 "Hello World" 程序开始。创建文件 hello.js,写入以下代码:
console.log("Hello, Node.js!");
在终端中运行:
node hello.js
你会看到输出 Hello, Node.js!。
Node.js 的一个常见用途是创建 Web 服务器。以下代码创建一个简单的 HTTP 服务器,当访问 http://localhost:3000 时返回 "Hello World":
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(3000, '127.0.0.1', () => {
console.log('服务器运行在 http://127.0.0.1:3000/');
});
将代码保存为 server.js,运行 node server.js,然后在浏览器中打开 http://127.0.0.1:3000,你将看到 "Hello World"。
Node.js 采用 CommonJS 模块规范,每个文件都是一个独立的模块。模块通过 require 函数引入,通过 module.exports 或 exports 导出。
例如,创建一个模块 math.js:
// math.js
const add = (a, b) => a + b;
const subtract = (a, b) => a - b;
module.exports = { add, subtract };
然后在另一个文件中使用它:
// app.js
const math = require('./math.js');
console.log(math.add(5, 3)); // 输出 8
npm 是 Node.js 的默认包管理器,用于安装、管理和发布模块。常用命令:
npm init - 初始化项目,创建 package.json 文件。npm install <包名> - 安装一个包,并自动添加到 dependencies。npm install -g <包名> - 全局安装包。npm uninstall <包名> - 卸载包。例如,安装一个流行的框架 express:
npm install express
Node.js 大量使用异步操作,避免阻塞。传统的异步处理方式是回调函数,但回调嵌套过深会导致“回调地狱”。现代 Node.js 支持 Promise 和 async/await,使异步代码更易读。
例如,使用 fs 模块读取文件(异步回调版):
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
使用 Promise 版本(fs.promises):
const fs = require('fs').promises;
fs.readFile('file.txt', 'utf8')
.then(data => console.log(data))
.catch(err => console.error(err));
使用 async/await:
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('file.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();
Node.js 让 JavaScript 走出浏览器,成为服务端开发的利器。它凭借事件驱动和非阻塞 I/O 模型,在高并发场景下表现优异。通过 npm 生态系统,开发者可以快速构建各种应用。下一章我们将详细介绍 Node.js 的安装与环境配置。