Node.js 是前端开发人员进军后端的重要工具之一。本文将带领你从 0 开始了解 Node.js 的基本概念、安装配置、核心模块及实战案例,让你快速入门 Node.js!
一、什么是 Node.js?
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,它能够让 JavaScript 不仅运行在浏览器内,还能用于服务器端开发。Node.js 提供了一整套工具和模块,使 JavaScript 在服务器端可以处理文件、数据库和 HTTP 请求等任务。
二、Node.js 的安装
1. 下载 Node.js
前往 Node.js 官方网站:https://nodejs.org/,下载适合你操作系统的安装包。推荐选择 LTS(长期支持版),更加稳定。
2. 安装并验证
-
下载完成后运行安装文件,一路点击“下一步”完成安装。
-
安装完成后,打开命令行(Windows 上是 CMD 或 PowerShell,macOS 是 Terminal),输入以下命令验证是否安装成功:
node -v npm -v
以上命令会输出 Node.js 和 npm 的版本号,表明安装成功。
三、Node.js 核心概念
1. 模块化
Node.js 使用模块化开发模式。每个文件都可以看作是一个模块,可以通过 require
引用其他模块。
2. 同步与异步
Node.js 支持非阻塞的异步操作,这是它在高并发场景下表现优异的原因。
3. 事件驱动
Node.js 采用事件驱动的方式,当事件触发时会执行回调函数。
四、Node.js 入门代码示例
1. Hello, World!
新建一个 hello.js
文件,输入以下代码:
console.log("Hello, World!");
在命令行中运行:
node hello.js
输出:
Hello, World!
2. 搭建第一个 HTTP 服务器
Node.js 内置了 http
模块,可以轻松创建 HTTP 服务器。
// server.js
const http = require('http');
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, Node.js Server!
');
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
运行此代码后,访问 http://localhost:3000 就能看到 Hello, Node.js Server!
的内容。
3. 使用模块化:创建和调用模块
-
创建一个
math.js
文件,定义一个简单的加法函数:// math.js function add(a, b) { return a + b; } module.exports = { add };
-
在主文件
app.js
中使用require
引入模块:// app.js const math = require('./math'); const result = math.add(2, 3); console.log("2 + 3 =", result);
运行 app.js
,会看到输出:
2 + 3 = 5
五、Node.js 常用模块
1. 文件系统模块 fs
Node.js 提供 fs
模块用于文件的读写操作。
示例:读取文件内容
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) {
console.error(err);
return;
}
console.log(data);
});
2. 路径模块 path
path
模块用于处理和转换文件路径。
const path = require('path');
const fullPath = path.join(__dirname, 'example', 'test.txt');
console.log(fullPath); // 输出完整路径
3. URL 模块 url
url
模块提供了对 URL 字符串的解析、拼接等操作。
const url = require('url');
const myURL = new URL('https://www.example.com:8000/path/name?foo=bar#hash');
console.log(myURL.hostname); // 输出:www.example.com
console.log(myURL.searchParams.get('foo')); // 输出:bar
六、Node.js 异步编程与回调
1. 使用回调函数
const fs = require('fs');
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
2. 使用 Promise
Node.js 也支持使用 Promise 来处理异步操作:
const fs = require('fs').promises;
fs.readFile('example.txt', 'utf8')
.then(data => {
console.log(data);
})
.catch(err => {
console.error(err);
});
3. 使用 Async/Await
在 Node.js 中使用 async/await
可以更加简洁地处理异步逻辑:
const fs = require('fs').promises;
async function readFile() {
try {
const data = await fs.readFile('example.txt', 'utf8');
console.log(data);
} catch (err) {
console.error(err);
}
}
readFile();
七、Node.js 项目实战:简易 API 接口
以下代码实现了一个简单的 API 服务,可以处理 HTTP 请求,并返回 JSON 数据。
1. 创建 apiServer.js
const http = require('http');
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'application/json');
res.setHeader('Access-Control-Allow-Origin', '*');
if (req.url === '/api' && req.method === 'GET') {
const data = { message: 'Hello from Node.js API!' };
res.writeHead(200);
res.end(JSON.stringify(data));
} else {
res.writeHead(404);
res.end(JSON.stringify({ error: 'Resource not found' }));
}
});
server.listen(4000, () => {
console.log('API server running on http://localhost:4000');
});
2. 启动 API 服务器
在终端运行以下命令启动服务器:
node apiServer.js
打开浏览器或使用 API 测试工具访问 http://localhost:4000/api,应该会得到如下响应:
{
"message": "Hello from Node.js API!"
}
八、总结
通过本篇文章,你应该已经掌握了 Node.js 的基础操作,了解了如何创建和使用模块、如何处理文件系统以及如何构建一个简单的 HTTP 服务器。掌握 Node.js 的这些基础知识后,你可以进一步学习 Express 框架、数据库连接、WebSocket 等内容,不断扩展 Node.js 的使用场景。
希望这篇文章能帮助你快速入门 Node.js!