Node.js全棧知識(shí)點(diǎn)超詳細(xì)整理(含代碼示例+前端結(jié)合實(shí)戰(zhàn))
前端
本文從基礎(chǔ)到進(jìn)階全面梳理 Node.js 核心知識(shí)點(diǎn),并重點(diǎn)詳解前端與 Node.js 的 6 種核心結(jié)合方式(前后端分離、SSR、靜態(tài)服務(wù)、跨域代理、工程化、全棧實(shí)戰(zhàn)),覆蓋前端開發(fā)必備的 Node.js 全量知識(shí)。
一、Node.js 基礎(chǔ)核心
1.1 Node.js 簡(jiǎn)介與運(yùn)行
Node.js 是基于 Chrome V8 引擎的 JavaScript 運(yùn)行時(shí),讓 JS 可以運(yùn)行在服務(wù)端,核心特性:非阻塞 I/O、事件驅(qū)動(dòng)、輕量高效。
- 安裝:官網(wǎng)下載對(duì)應(yīng)系統(tǒng)安裝包(自帶
npm包管理器) - 運(yùn)行:終端執(zhí)行
node 文件名.js
1.2 全局對(duì)象 & 全局 API
Node.js 無瀏覽器的 window,替代為 global 全局對(duì)象,內(nèi)置常用全局 API:
| 全局對(duì)象 / API | 作用 | 代碼示例 |
|---|---|---|
global | 全局根對(duì)象 | global.name = "Node.js"; console.log(global.name) |
process | 進(jìn)程信息(環(huán)境變量、命令行參數(shù)) | js // 打印環(huán)境變量 console.log(process.env); // 命令行參數(shù) console.log(process.argv); |
__dirname | 當(dāng)前文件所在絕對(duì)路徑 | console.log(__dirname) |
__filename | 當(dāng)前文件的絕對(duì)路徑 + 文件名 | console.log(__filename) |
| 定時(shí)器 | setTimeout/setInterval/setImmediate | setTimeout(()=>console.log("延時(shí)執(zhí)行"),1000) |
1.3 核心內(nèi)置模塊(必學(xué))
Node.js 內(nèi)置無需安裝的核心模塊,是服務(wù)端開發(fā)基礎(chǔ):
1. Buffer 模塊(二進(jìn)制數(shù)據(jù)處理)
處理文件、網(wǎng)絡(luò)傳輸的二進(jìn)制數(shù)據(jù)(Node.js 特有)
// 創(chuàng)建 Buffer
const buf = Buffer.from('Hello Node.js', 'utf8');
// 轉(zhuǎn)字符串
console.log(buf.toString()); // Hello Node.js
// 查看二進(jìn)制
console.log(buf); // <Buffer 48 65 6c 6c 6f 20 4e 6f 64 65 2e 6a 73>
2. fs 模塊(文件系統(tǒng))
文件讀寫、復(fù)制、刪除,分同步 / 異步兩種寫法(推薦異步,非阻塞)
const fs = require('fs'); // 引入模塊
// 1. 異步讀取文件(推薦)
fs.readFile('test.txt', 'utf8', (err, data) => {
if (err) throw err; // 錯(cuò)誤處理
console.log('文件內(nèi)容:', data);
});
// 2. 同步讀取文件(阻塞線程,慎用)
const data = fs.readFileSync('test.txt', 'utf8');
// 3. 寫入文件(覆蓋寫入)
fs.writeFile('test.txt', '我是寫入的內(nèi)容', (err) => {
if (!err) console.log('寫入成功');
});
3. path 模塊(路徑處理)
解決跨平臺(tái)路徑兼容問題(Windows/macOS/Linux)
const path = require('path');
// 拼接絕對(duì)路徑(最常用)
const fullPath = path.join(__dirname, 'test.txt');
console.log('完整路徑:', fullPath);
// 獲取文件名
console.log(path.basename(fullPath)); // test.txt
// 獲取文件擴(kuò)展名
console.log(path.extname(fullPath)); // .txt
4. http 模塊(原生 Web 服務(wù))
創(chuàng)建 HTTP 服務(wù)器,處理前端請(qǐng)求
const http = require('http');
// 創(chuàng)建服務(wù)器
const server = http.createServer((req, res) => {
// 設(shè)置響應(yīng)頭
res.writeHead(200, { 'Content-Type': 'text/plain;charset=utf-8' });
// 返回響應(yīng)內(nèi)容
res.end('Hello Node.js 原生服務(wù)器');
});
// 監(jiān)聽 3000 端口
server.listen(3000, () => {
console.log('服務(wù)器運(yùn)行在 http://localhost:3000');
});
5. events 模塊(事件驅(qū)動(dòng))
Node.js 核心:基于事件訂閱 / 發(fā)布
const EventEmitter = require('events');
const emitter = new EventEmitter();
// 1. 訂閱事件(監(jiān)聽)
emitter.on('sayHi', (name) => {
console.log(`你好,${name}`);
});
// 2. 觸發(fā)事件
emitter.emit('sayHi', '前端開發(fā)者');
1.4 模塊化系統(tǒng)
Node.js 采用模塊化管理代碼,避免全局污染,支持兩種規(guī)范:
1. CommonJS 規(guī)范(默認(rèn))
- 導(dǎo)出:
module.exports/exports - 導(dǎo)入:
require()
// 模塊文件:utils.js
// 導(dǎo)出
module.exports = {
sum: (a, b) => a + b,
name: "工具模塊"
};
// 主文件:index.js
const utils = require('./utils.js');
console.log(utils.sum(1,2)); // 3
2. ES Module 規(guī)范(ESM,現(xiàn)代推薦)
需在 package.json 中添加 "type": "module"
// 模塊文件:utils.js
// 導(dǎo)出
export const sum = (a,b) => a+b;
export const name = "工具模塊";
// 主文件:index.js
import { sum, name } from './utils.js';
console.log(sum(1,2)); // 3
1.5 異步編程(Node.js 核心)
Node.js 是異步非阻塞模型,解決回調(diào)地獄的三種方案:
1. 回調(diào)函數(shù)(原始寫法,易產(chǎn)生回調(diào)地獄)
fs.readFile('a.txt', 'utf8', (err, data1) => {
fs.readFile('b.txt', 'utf8', (err, data2) => {
console.log(data1 + data2); // 嵌套層級(jí)過深 = 回調(diào)地獄
});
});
2. Promise(優(yōu)化嵌套)
const fs = require('fs/promises'); // Promise 版 fs
fs.readFile('a.txt', 'utf8')
.then(data1 => fs.readFile('b.txt', 'utf8'))
.then(data2 => console.log(data2))
.catch(err => console.log(err));
3. async/await(終極方案,同步寫法寫異步)
const fs = require('fs/promises');
// 異步函數(shù)
async function readFiles() {
try {
const data1 = await fs.readFile('a.txt', 'utf8');
const data2 = await fs.readFile('b.txt', 'utf8');
console.log(data1 + data2);
} catch (err) {
console.log('讀取失?。?, err);
}
}
readFiles(); // 執(zhí)行
二、Node.js Web 開發(fā)(前端結(jié)合核心)
原生 http 模塊開發(fā)效率低,Express 是 Node.js 最流行的 Web 框架(輕量、靈活)。
2.1 Express 快速上手
- 安裝:
npm install express - 基礎(chǔ)服務(wù)器:
const express = require('express');
const app = express();
const PORT = 3000;
// 1. 中間件:解析 JSON 請(qǐng)求體(處理前端 POST 數(shù)據(jù))
app.use(express.json());
// 2. 中間件:解決跨域(后面前端結(jié)合會(huì)詳解)
const cors = require('cors');
app.use(cors());
// 3. 路由:處理 GET 請(qǐng)求
app.get('/', (req, res) => {
res.send('Hello Express 服務(wù)器');
});
// 4. 動(dòng)態(tài)路由
app.get('/user/:id', (req, res) => {
res.json({ id: req.params.id, name: '前端用戶' });
});
// 啟動(dòng)服務(wù)
app.listen(PORT, () => {
console.log(`Express 運(yùn)行在 http://localhost:${PORT}`);
});
2.2 常用中間件
中間件是 Express 的核心,處理請(qǐng)求 / 響應(yīng)的通用邏輯:
| 中間件 | 作用 | 安裝 |
|---|---|---|
cors | 解決跨域 | npm i cors |
multer | 文件上傳 | npm i multer |
dotenv | 環(huán)境變量管理 | npm i dotenv |
express.static | 靜態(tài)資源托管 | 內(nèi)置 |
三、數(shù)據(jù)持久化(數(shù)據(jù)庫(kù))
Node.js 配合數(shù)據(jù)庫(kù)實(shí)現(xiàn)數(shù)據(jù)存儲(chǔ),前端常用組合:
- 非關(guān)系型:MongoDB + Mongoose
- 關(guān)系型:MySQL + mysql2
示例:MongoDB + Mongoose
// 安裝:npm i mongoose
const mongoose = require('mongoose');
// 1. 連接數(shù)據(jù)庫(kù)
mongoose.connect('mongodb://localhost:27017/frontDB')
.then(() => console.log('MongoDB 連接成功'));
// 2. 定義數(shù)據(jù)模型
const userSchema = new mongoose.Schema({
username: String,
age: Number
});
const User = mongoose.model('User', userSchema);
// 3. 新增數(shù)據(jù)(給前端接口用)
async function addUser() {
const user = new User({ username: '前端小白', age: 22 });
await user.save();
}
addUser();
重點(diǎn):前端與 Node.js 結(jié)合實(shí)戰(zhàn)(6 大場(chǎng)景)
這是前端開發(fā)最常用的 Node.js 應(yīng)用場(chǎng)景,每個(gè)場(chǎng)景配前后端完整代碼 + 詳細(xì)闡述。
場(chǎng)景 1:前后端分離(主流)
核心邏輯
- Node.js(Express):寫后端 API 接口(提供數(shù)據(jù))
- 前端:用
axios請(qǐng)求接口,渲染頁面(Vue/React/ 原生 JS 通用)
步驟 1:Node.js 編寫 API 接口
// server.js(后端)
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.json());
// 模擬數(shù)據(jù)
const users = [
{ id:1, name:'張三', job:'前端開發(fā)' },
{ id:2, name:'李四', job:'全棧開發(fā)' }
];
// 1. GET 接口:獲取用戶列表
app.get('/api/users', (req, res) => {
res.json(users); // 返回 JSON 數(shù)據(jù)
});
// 2. POST 接口:新增用戶
app.post('/api/user', (req, res) => {
const newUser = req.body; // 接收前端傳遞的數(shù)據(jù)
users.push(newUser);
res.json({ msg:'新增成功', user:newUser });
});
app.listen(3000, () => console.log('API 服務(wù)運(yùn)行在 3000 端口'));
步驟 2:前端請(qǐng)求接口(原生 HTML + Axios)
<!-- index.html(前端) -->
<!DOCTYPE html>
<html>
<body>
<div id="userList"></div>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
// 1. 請(qǐng)求后端接口獲取用戶
async function getUsers() {
const res = await axios.get('http://localhost:3000/api/users');
// 渲染數(shù)據(jù)到頁面
const html = res.data.map(item => `<p>${item.name} - ${item.job}</p>`).join('');
document.getElementById('userList').innerHTML = html;
}
// 2. 調(diào)用接口
getUsers();
</script>
</body>
</html>
前端結(jié)合闡述
- 解耦:前端專注頁面渲染,后端專注數(shù)據(jù)接口,獨(dú)立開發(fā)部署
- 技術(shù)棧:Vue/React + Axios + Node.js/Express 是前端主流全棧方案
- 跨域:后端用
cors中間件解決前端跨域問題
場(chǎng)景 2:靜態(tài)資源服務(wù)器
核心邏輯
Node.js 托管前端靜態(tài)文件(HTML/CSS/JS/ 圖片),直接訪問頁面。
后端代碼
const express = require('express');
const app = express();
// 托管當(dāng)前目錄下的 public 文件夾(存放前端靜態(tài)文件)
app.use(express.static('public'));
app.listen(3000, () => {
console.log('靜態(tài)服務(wù)器運(yùn)行在 http://localhost:3000');
});
目錄結(jié)構(gòu)
├── server.js
└── public/ # 前端靜態(tài)資源
├── index.html
├── css/style.css
└── js/main.js前端結(jié)合闡述
- 無需 Nginx,Node.js 快速搭建前端靜態(tài)服務(wù)
- 適用于:前端項(xiàng)目本地預(yù)覽、小型項(xiàng)目部署
場(chǎng)景 3:服務(wù)端渲染(SSR)
核心邏輯
Node.js 在服務(wù)端渲染頁面,直接返回完整 HTML 給前端(利于 SEO,首屏快)。
步驟 1:Express + EJS 模板引擎
// 安裝:npm i ejs
const express = require('express');
const app = express();
// 配置模板引擎
app.set('view engine', 'ejs');
// 模板文件目錄
app.set('views', './views');
// 渲染頁面
app.get('/', (req, res) => {
// 向模板傳遞數(shù)據(jù)
res.render('index', { title: 'Node.js SSR 頁面', user: '前端開發(fā)者' });
});
app.listen(3000);
步驟 2:EJS 模板(前端頁面)
<!-- views/index.ejs --> <h1><%= title %></h1> <p>歡迎:<%= user %></p>
前端結(jié)合闡述
- 解決 SPA(單頁應(yīng)用)SEO 不友好、首屏加載慢問題
- 適用場(chǎng)景:官網(wǎng)、博客、電商等需要 SEO 的頁面
場(chǎng)景 4:開發(fā)環(huán)境跨域代理
核心問題
前端開發(fā)時(shí)請(qǐng)求第三方接口會(huì)跨域,用 Node.js 做代理服務(wù)器轉(zhuǎn)發(fā)請(qǐng)求。
后端代理代碼
// 安裝:npm i http-proxy-middleware
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
// 代理配置:將 /api 請(qǐng)求轉(zhuǎn)發(fā)到第三方接口
app.use('/api', createProxyMiddleware({
target: 'https://api.github.com', // 第三方接口地址
changeOrigin: true // 解決跨域
}));
app.listen(3001, () => console.log('代理服務(wù)器運(yùn)行在 3001 端口'));
前端請(qǐng)求
// 前端請(qǐng)求代理服務(wù)器,而非直接請(qǐng)求第三方接口
axios.get('http://localhost:3001/api/users')
.then(res => console.log(res.data));
前端結(jié)合闡述
- 替代 Webpack/Vite 內(nèi)置代理,純 Node.js 實(shí)現(xiàn)跨域代理
- 適用于:無構(gòu)建工具的原生前端項(xiàng)目開發(fā)
場(chǎng)景 5:前端工程化(Node.js 驅(qū)動(dòng))
核心邏輯
Node.js 是前端工程化的基石,所有構(gòu)建工具都基于 Node.js 開發(fā):
- 包管理:
npm/yarn/pnpm - 構(gòu)建工具:
Webpack/Vite/Rollup - 腳本命令:
package.json中的scripts
示例:package.json 腳本
{
"scripts": {
"dev": "vite", // 啟動(dòng)開發(fā)服務(wù)(Node.js 驅(qū)動(dòng))
"build": "vite build", // 打包項(xiàng)目
"preview": "vite preview"
}
}
前端結(jié)合闡述
- 前端的模塊化、打包、壓縮、熱更新全靠 Node.js 實(shí)現(xiàn)
- Vue/React 項(xiàng)目的底層運(yùn)行環(huán)境都是 Node.js
場(chǎng)景 6:全棧小案例(TODO 待辦)
完整演示:前端頁面 + Node.js 接口 + 數(shù)據(jù)存儲(chǔ)
- 前端:增刪改查待辦事項(xiàng)
- Node.js:提供 CRUD 接口
- 數(shù)據(jù):內(nèi)存存儲(chǔ)(可替換為數(shù)據(jù)庫(kù))
四、Node.js 進(jìn)階知識(shí)點(diǎn)
流(Stream) :處理大文件(視頻 / 日志),避免內(nèi)存溢出
const fs = require('fs'); // 讀取流 const readStream = fs.createReadStream('largeFile.txt'); readStream.on('data', (chunk) => console.log('讀取分片:', chunk));進(jìn)程管理:
child_process(創(chuàng)建子進(jìn)程)、pm2(生產(chǎn)環(huán)境部署)錯(cuò)誤處理:全局異常捕獲、接口錯(cuò)誤統(tǒng)一返回
部署:服務(wù)器安裝 Node.js,用
pm2守護(hù)進(jìn)程
總結(jié)
Node.js 核心:非阻塞 I/O、事件驅(qū)動(dòng)、模塊化、異步編程(async/await)
Web 開發(fā):Express 是前端必備框架,核心是路由 + 中間件
前端結(jié)合:
- 主流:前后端分離(Node.js 寫 API,前端請(qǐng)求)
- 輔助:靜態(tài)服務(wù)、跨域代理、SSR、工程化
全棧能力:前端掌握 Node.js,可獨(dú)立完成「前端頁面 + 后端接口 + 部署」全流程開發(fā)
到此這篇關(guān)于Node.js全棧知識(shí)點(diǎn)超詳細(xì)整的文章就介紹到這了,更多相關(guān)Node.js全棧知識(shí)點(diǎn)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js實(shí)現(xiàn)文本與pdf相互轉(zhuǎn)換的代碼詳解
在IT行業(yè)中,文檔格式轉(zhuǎn)換是日常工作中的常見需求,Word與PDF是兩種廣泛應(yīng)用的文檔格式,它們各有優(yōu)勢(shì),但有時(shí)需要相互轉(zhuǎn)換以滿足特定場(chǎng)景的需求,本篇將詳細(xì)講解如何使用Node.js實(shí)現(xiàn)文本與pdf相互轉(zhuǎn)換,需要的朋友可以參考下2025-07-07
node.js報(bào)錯(cuò):npm?ERR?code?EPERM的解決過程
在學(xué)習(xí)vue+typescript的時(shí)候突然發(fā)現(xiàn)了個(gè)錯(cuò)誤,所以下面這篇文章主要給大家介紹了關(guān)于node.js報(bào)錯(cuò):npm?ERR?code?EPERM的詳細(xì)解決過程,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
Node.js對(duì)MongoDB進(jìn)行增刪改查操作的實(shí)例代碼
這篇文章主要介紹了Node.js對(duì)MongoDB進(jìn)行增刪改查操作 ,需要的朋友可以參考下2019-04-04

