Node.js 的核心能力之一就是快速创建高性能的服务器。通过内置的
http和https模块,你可以在几行代码内搭建功能完善的 Web 服务。本文将系统讲解如何在 Node.js 中创建 HTTP 与 HTTPS 服务器,包括基础用法、请求处理、HTTPS 证书配置,以及性能与安全优化实践。
一、Node.js HTTP 服务器基础
Node.js 内置的 http 模块让创建 HTTP 服务器非常简单。
1. 基本示例
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 HTTP Server!");
});
server.listen(3000, () => {
console.log("Server running at http://localhost:3000/");
});
说明:
http.createServer返回一个服务器实例- 回调函数
(req, res)在每次请求到来时触发 req包含请求信息,res用于发送响应server.listen绑定端口并启动服务器
二、处理请求与响应
HTTP 请求包含方法、URL、头信息和请求体。响应也可以设置状态码、头信息及数据。
js
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
res.writeHead(200, { "Content-Type": "text/html" });
res.end("<h1>Welcome Home</h1>");
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Page Not Found");
}
});
技巧与建议:
- 对请求进行路由判断,区分不同路径和方法
- 响应头要根据内容类型设置
- 大型项目可使用第三方框架如 Express 做路由和中间件管理
三、Node.js HTTPS 服务器
在实际生产环境中,HTTPS 已经是必须。Node.js 提供 https 模块支持加密传输。
1. 准备证书
创建 HTTPS 服务器前,需要拥有:
key.pem:私钥文件cert.pem:证书文件(可以用自签名证书做测试)
可以使用 OpenSSL 生成测试证书:
bash
openssl req -nodes -new -x509 -keyout key.pem -out cert.pem
2. 创建 HTTPS 服务器
js
const https = require("https");
const fs = require("fs");
const options = {
key: fs.readFileSync("key.pem"),
cert: fs.readFileSync("cert.pem")
};
const server = https.createServer(options, (req, res) => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end("Hello Node.js HTTPS Server!");
});
server.listen(3443, () => {
console.log("HTTPS Server running at https://localhost:3443/");
});
注意事项:
- HTTPS 必须提供证书和私钥
- 在生产环境中,请使用由可信 CA 签发的证书
- 端口一般为 443(HTTP 默认端口为 80)
四、性能优化建议
虽然 Node.js 的 http 和 https 模块足够轻量,但在高并发场景下,仍然可以优化:
- 开启 Keep-Alive 保持 TCP 连接,减少握手开销:
js
res.setHeader("Connection", "keep-alive");
- 使用 gzip 压缩 减少传输数据量,提高响应速度:
js
const zlib = require("zlib");
res.writeHead(200, { "Content-Encoding": "gzip" });
res.end(zlib.gzipSync("Hello World!"));
- 利用集群(cluster)提升 CPU 利用率 Node.js 单线程模型可以通过 cluster 模块启动多进程:
js
const cluster = require("cluster");
const os = require("os");
if (cluster.isMaster) {
const cpuCount = os.cpus().length;
for (let i = 0; i < cpuCount; i++) {
cluster.fork();
}
} else {
// worker 进程启动 HTTP/HTTPS 服务器
}
- 使用缓存 对静态文件或接口数据使用内存缓存或 CDN,降低重复计算和 I/O 压力。
五、常见应用场景
- 搭建静态文件服务器
- 提供 RESTful API 服务
- 接入 WebSocket 做实时通信
- 内网工具或微服务
- HTTPS 接入支付、认证等安全场景
Node.js 的 HTTP/HTTPS 服务器能力非常适合高并发和轻量服务场景。
六、总结
通过本文,你应该掌握了:
- HTTP 服务器的创建与请求处理
- HTTPS 服务器的证书配置和创建
- 异步请求处理与响应机制
- 高性能与安全优化策略
Node.js 内置的 HTTP/HTTPS 模块简单高效,非常适合构建高性能微服务和 API。 理解这些基础,为使用 Express、Koa 等框架打下了坚实的底层基础。