Node.js 入门指南:前端开发者快速上手
作为 Vue 前端开发者,学习 Node.js 可以让你解锁全栈开发能力。本文将从零开始介绍 Node.js,用简单易懂的方式带你快速入门。
一、什么是 Node.js?
Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,它让 JavaScript 可以运行在服务器端。简单来说:
- 浏览器中的 JavaScript:操作 DOM、处理用户交互
- Node.js 中的 JavaScript:读写文件、连接数据库、处理网络请求
为什么前端要学 Node.js?
- 可以开发全栈应用(前后端都用 JavaScript)
- 使用 npm 生态更深入(许多前端工具基于 Node.js)
- 开发后端 API 供前端调用
- 编写构建工具和脚本
二、安装 Node.js
- 前往 Node.js 官网 下载 LTS 版本
- 安装完成后,在终端验证:
node -v # 查看 Node.js 版本
npm -v # 查看 npm 版本
三、第一个 Node.js 程序
创建一个 app.js 文件:
// 这是 Node.js 代码
console.log('Hello Node.js!');
function add(a, b) {
return a + b;
}
console.log('1 + 2 =', add(1, 2));
运行它:
node app.js
你会看到控制台输出:
Hello Node.js!
1 + 2 = 3
四、Node.js 核心概念
1. 模块系统
Node.js 使用 CommonJS 模块系统(类似 ES6 的 import/export)
示例:创建和使用模块
math.js:
// 导出函数
exports.add = (a, b) => a + b;
exports.subtract = (a, b) => a - b;
app.js:
// 引入模块
const math = require('./math');
console.log('3 + 5 =', math.add(3, 5));
console.log('10 - 2 =', math.subtract(10, 2));
2. 内置模块
Node.js 提供了许多内置模块:
fs 文件系统模块
const fs = require('fs');
// 读取文件
fs.readFile('example.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log('文件内容:', data);
});
// 写入文件
fs.writeFile('output.txt', '这是写入的内容', (err) => {
if (err) throw err;
console.log('文件已保存');
});
http 创建服务器
const http = require('http');
// 创建服务器
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('<h1>Hello Node.js Server!</h1>');
});
// 监听端口
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});
运行后访问 http://localhost:3000 就能看到页面
五、npm 包管理
npm 是 Node.js 的包管理器,前端开发者已经很熟悉了。Node.js 开发中常用命令:
npm init # 初始化项目
npm install express # 安装 Express 框架
npm start # 启动项目
六、Express 框架快速上手
Express 是 Node.js 最流行的 Web 框架:
- 创建项目并安装 Express:
mkdir my-express-app
cd my-express-app
npm init -y
npm install express
- 创建
server.js:
const express = require('express');
const app = express();
const port = 3000;
// 路由
app.get('/', (req, res) => {
res.send('首页');
});
app.get('/api/users', (req, res) => {
res.json([{id: 1, name: '张三'}, {id: 2, name: '李四'}]);
});
// 启动服务器
app.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
- 运行服务器:
node server.js
现在你可以:
- 访问 http://localhost:3000 查看首页
- 访问 http://localhost:3000/api/users 获取用户数据
七、连接前端 Vue 应用
作为前端开发者,你可以用 Node.js 为 Vue 应用提供 API:
- 在 Vue 项目中调用 Node.js API:
// Vue 组件中
async fetchUsers() {
const response = await fetch('http://localhost:3000/api/users');
const users = await response.json();
this.users = users;
}
- 解决跨域问题(在 Express 中添加 CORS 支持):
npm install cors
const cors = require('cors');
app.use(cors()); // 启用 CORS
八、实用小技巧
-
nodemon:开发时自动重启 Node.js 应用
npm install -g nodemon nodemon server.js -
环境变量:使用
.env文件npm install dotenvrequire('dotenv').config(); console.log(process.env.PORT); -
异步编程:使用 async/await
const fs = require('fs').promises; async function readFile() { const data = await fs.readFile('file.txt', 'utf8'); console.log(data); }
九、下一步学习建议
- 学习 Express 路由和中间件
- 连接数据库(MongoDB 或 MySQL)
- 学习 RESTful API 设计
- 了解身份验证(JWT)
- 部署 Node.js 应用
作为 Vue 开发者,掌握 Node.js 后你将能够:
- 开发全栈应用
- 创建自定义 API
- 更好地理解现代前端工具链
- 扩展职业发展可能性
尝试用 Node.js 为你的下一个 Vue 项目构建一个简单的后端 API 吧!