Node.js 创建第一个应用
通过创建简单的 HTTP 服务器,了解 Node.js 应用的基本结构。
创建项目文件
Bash
# 创建项目目录
mkdir my-first-app
cd my-first-app
# 创建主文件
touch index.js # 或直接创建文件
编写 HTTP 服务器
JavaScript
// index.js
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
// 设置响应头
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
// 发送响应内容
res.end('<h1>Hello Node.js!</h1><p>这是我的第一个应用</p>');
});
// 监听端口
const PORT = 3000;
server.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
运行应用
Bash
# 运行文件
node index.js
# 输出: 服务器运行在 http://localhost:3000
# 浏览器访问 http://localhost:3000
# 显示: Hello Node.js!
处理不同路径
JavaScript
const http = require('http');
const server = http.createServer((req, res) => {
const url = req.url;
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
if (url === '/') {
res.end('<h1>首页</h1>');
} else if (url === '/about') {
res.end('<h1>关于页面</h1>');
} else if (url === '/api') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'API 响应' }));
} else {
res.writeHead(404);
res.end('<h1>404 未找到</h1>');
}
});
server.listen(3000, () => {
console.log('服务器启动');
});
使用 package.json 管理
Bash
# 初始化 package.json
npm init -y
修改 package.json:
JSON
{
"name": "my-first-app",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
}
Bash
# 使用 npm 脚本运行
npm start
# 安装 nodemon 自动重启
npm install nodemon -D
npm run dev
添加日志功能
JavaScript
// index.js
const http = require('http');
const server = http.createServer((req, res) => {
// 记录请求日志
const time = new Date().toISOString();
console.log(`[${time}] ${req.method} ${req.url}`);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>Hello</h1>');
});
server.listen(3000, () => {
console.log('服务器启动于 http://localhost:3000');
});
模块化拆分
JavaScript
// routes.js - 路由模块
module.exports = function(req, res) {
if (req.url === '/') {
res.end('<h1>首页</h1>');
} else if (req.url === '/about') {
res.end('<h1>关于</h1>');
} else {
res.writeHead(404);
res.end('<h1>404</h1>');
}
};
// index.js - 主文件
const http = require('http');
const router = require('./routes');
const server = http.createServer(router);
server.listen(3000);
终止应用
Bash
# 在终端按 Ctrl+C 终止运行
# 或使用 kill 命令(Linux/macOS)
kill <pid>
# Windows
taskkill /F /PID <pid>
项目结构建议
text
my-first-app/
├── index.js # 主入口文件
├── routes.js # 路由模块
├── package.json # 项目配置
├── package-lock.json
└── node_modules/ # 依赖目录
要点总结
- 使用 http.createServer 创建服务器
- res.writeHead 设置响应头,res.end 发送内容
- server.listen 启动监听端口
- 使用 npm scripts 管理运行命令
- nodemon 实现开发时自动重启
- 模块化拆分提高代码可维护性
📝 发现内容有误?点击此处直接编辑