Node.js 入门指南:从零开始搭建你的第一个服务器
Node.js 是一个基于 Chrome V8 引擎构建的高效 JavaScript 运行时,它允许开发者使用 JavaScript 在服务端编写应用程序。作为全栈开发者的标配技能之一,Node.js 已经成为构建高效、可扩展网络应用的主力工具。
这篇文章是 Node.js 的入门指南,我们将带你从零开始搭建一个简单的服务器,了解 Node.js 的核心概念和用法。
目录
1. 什么是 Node.js?
Node.js 是一个开源、跨平台的运行时环境,可以让 JavaScript 脱离浏览器环境,在服务端执行。它的核心特点包括:
- 事件驱动、非阻塞 I/O:通过异步操作提高性能。
- 轻量高效:适合 I/O 密集型和实时应用。
- 单线程:通过事件循环机制高效处理并发请求。
Node.js 的典型应用场景包括:
- 构建 RESTful API
- 实现实时聊天系统
- 构建微服务架构
2. 安装 Node.js
检查 Node.js 是否已安装
在终端中输入以下命令:
node -v
如果输出版本号(例如 v18.0.0),说明 Node.js 已经安装;如果未安装,请按以下步骤操作。
安装 Node.js
安装完成后,再次检查版本:
node -v
npm -v # 检查 npm(Node.js 包管理器)版本
3. 搭建第一个 Node.js 服务器
创建项目文件
cd node-server
touch server.js
编写代码
打开 server.js 文件,输入以下代码:
// 引入 http 模块
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/plain' });
// 返回响应内容
res.end('Hello, Node.js!');
});
// 监听端口
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
4. Node.js 代码解析
-
require('http') Node.js 的核心模块之一,用于创建 HTTP 服务器。
-
http.createServer(callback) 创建一个服务器实例,callback 是处理请求的函数,其中包含 req(请求对象)和 res(响应对象)。
-
res.writeHead(statusCode, headers) 设置 HTTP 响应头,例如状态码 200 表示成功。
-
res.end(data) 结束响应并发送数据到客户端。
-
server.listen(port, callback) 启动服务器并监听指定端口,callback 是服务器启动后的回调函数。
5. 扩展功能:处理动态请求
在上一节中,我们实现了一个简单的静态服务器,现在我们尝试扩展它来响应不同的 URL:
修改代码
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (req.url === '/') {
res.end('Welcome to the Home Page!');
} else if (req.url === '/about') {
res.end('This is the About Page.');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
测试代码
启动服务器并在浏览器访问以下 URL:
- http://localhost:3000/ 显示 “Welcome to the Home Page!”
- http://localhost:3000/about 显示 “This is the About Page.”
- 访问其他 URL,例如 http://localhost:3000/unknown,返回 “404 Not Found”。
6. 总结与下一步
通过这篇入门教程,你已经掌握了以下内容:
接下来,你可以探索以下主题:
- 如何使用 Express 框架简化路由处理。
- 学习 RESTful API 的实现方法。
- 使用 Node.js 操作数据库,构建更复杂的应用程序。
Node.js 的世界充满可能性,现在开始你的探索之旅吧!如果有任何问题,欢迎留言讨论。
评论前必须登录!
注册