Node.js

Node.js基础

模块系统

require & module

CommonJS规范

模块化:把代码按功能分开(可复用性强)

举例

1
2
3
function sayHello(name) {
return `Hello, ${name}`
}
1
2
3
4
5
6
7
8
const express = require('express');//引入express模块
const sayHello = require('./myModule');//引入自定义模块

const app = express();

app.get('/', (req, res) => {
res.send(sayHello('World'));
});

npm包管理

就是前端常见的 npm install 下包

异步编程

回调函数Promise

可以通过 util.promisify将基于回调的API转换为返回Promise的形式

async关键字定义一个返回Promise的函数,await等待一个Promise对象的结果

fs.readFile

Node.js的文件系统模块(fs)提供了同步和异步两种版本的API,如 fs.readFilefs.readFileSync

四种写法

image-20250207162038459.png

HTTP服务器

引入nodejs内置模块

1
2
const http = require('http');
const url = require('url');

创建服务器

http.createServer()函数创建一个新的HTTP服务器实例

1
2
3
const server = http.createServer((req, res) => {
// 处理请求和响应
});

当有请求到达服务器时,回调函数会被触发

req是请求对象,res是响应对象

解析URL

1
const parsedUrl = url.parse(req.url, true);

req.url:获取请求的URL(比如 /hello?name=Qwen

url.parse():将URL拆解成对象,第二个参数 true表示将查询参数(如 ?name=Qwen)解析为对象(parsedUrl.query

设置响应头

1
res.writeHead(200, {'Content-Type': 'text/plain'});

状态码200:表示请求成功

Content-Type: text/plain:告诉浏览器返回的内容是纯文本

处理请求

req.url

req.method

1
2
3
4
5
6
7
8
9
if (req.method === 'GET') {
if (parsedUrl.pathname === '/hello') {//http://localhost:3000/hello?...=...
// 处理/hello路径
} else {
// 处理其他路径
}
} else {
// 处理非GET请求
}

路径是 /hello

1
2
let name = parsedUrl.query.name || "World";
res.end(`Hello ${name}!\n`);

获取查询参数:从 parsedUrl.query中读取 name参数(如 ?name=Qwen

如果未提供 name,默认值为 World

示例:访问 http://localhost:3000/hello?name=Qwen会返回 Hello Qwen!

其他路径

1
res.end('Welcome to the simple HTTP server!\n');

根路径示例:访问 http://localhost:3000/会返回欢迎消息

非get请求

1
2
res.writeHead(405, {'Content-Type': 'text/plain'});
res.end('Method Not Allowed\n');

状态码405:表示服务器不支持该请求方法(如POST、PUT等)

会返回错误信息 Method Not Allowed

启动服务器

1
2
3
server.listen(3000, () => {
console.log('Server is listening on port 3000');
});

服务器监听本地的3000端口,启动后打印日志。

调试与部署

nodemon热重载

nodemon是一个用于Node.js应用的工具,它可以监听文件变化并在文件被修改时自动重启服务,这大大提高了开发效率

PM2进程管理

它可以保证你的应用程序始终在线,即使遇到崩溃也能自动重启

1
pm2 start app.js --name "MyApi"

app.js就是你Node.js应用的入口文件

安装

1
npm install express nodemon pm2 --save