郑州做网站托管,门户网站开发费需入无形资产,在百度做推广送网站好吗,北京微信网站设计报价Node.js 零 基础入门与核心语法
适用对象#xff1a;完全没接触过 Node.js 的同学
目标#xff1a;从 0 到能写 CLI、小型 HTTP 服务、文件脚本、调用系统/网络资源
目录
什么是 Node.js安装与运行运行脚本与 REPL模块体系#xff1a;CommonJS 与 ES Modules基础语法在 Node…Node.js 零 基础入门与核心语法
适用对象完全没接触过 Node.js 的同学
目标从 0 到能写 CLI、小型 HTTP 服务、文件脚本、调用系统/网络资源
目录
什么是 Node.js安装与运行运行脚本与 REPL模块体系CommonJS 与 ES Modules基础语法在 Node 环境下的差异与全局对象内置核心模块概览与常用模块异步编程回调 → Promise → async/await事件循环与微任务/宏任务Node 特性Buffer 与二进制Stream流与管道、背压HTTP原生 http 模块使用 Express 快速开发环境变量与配置调试、热重载、脚手架实战小项目骨架原生与 Express常见错误与最佳实践1. 什么是 Node.js
Node.js 是一个基于 V8 引擎的 JavaScript 运行时提供了对文件、网络、进程等系统能力的访问。单线程、事件驱动、非阻塞 I/O擅长 I/O 密集任务HTTP 网关、代理、BFF、CLI、任务脚本等。2. 安装与运行
建议安装 LTS 版本https://nodejs.org/包管理器npm 随 Node 附带也可以用 yarn / pnpm常用命令
node -v
npm -v
npm config set registry https://registry.npmmirror.com # 切国内镜像可选3. 运行脚本与 REPL
运行文件node app.js交互式 REPLnode 回车后直接执行表达式
// app.js
console.log(Hello Node);4. 模块体系CommonJS 与 ES Modules
Node 支持两种模块系统。
A) CommonJSCJS默认
文件后缀通常 .jsrequire() 引入module.exports/exports 导出
// lib/math.js (CommonJS)
exports.add (a,b) a b;// app.js
const { add } require(./lib/math);
console.log(add(2,3));B) ES ModulesESM
在 package.json 中设置 type: module或使用 .mjs 后缀使用 import / export
// package.json
{name: demo,type: module,version: 1.0.0
}// lib/math.js (ESM)
export const add (a,b) a b;// app.js
import { add } from ./lib/math.js;
console.log(add(2,3));C) ESM 的 __dirname、__filename 替代
// ESM 获取当前文件路径
import { fileURLToPath } from node:url;
import { dirname } from node:path;const __filename fileURLToPath(import.meta.url);
const __dirname dirname(__filename);5. 基础语法在 Node 环境下的差异与全局对象
浏览器的 window 在 Node 中不存在Node 的全局是 global等价于 globalThis常见全局process/Buffer/__dirname(CJS)/setTimeout/console 等
console.log(globalThis global); // true
console.log(cwd, process.cwd()); // 当前工作目录6. 内置核心模块概览与常用模块
按频率与实用性排序以 ESM 写法CJS 用 require 即可
6.1 path路径拼接与解析
import path from node:path;console.log(path.join(/a, b, c.txt)); // \a\b\c.txt (win)
console.log(path.resolve(a/b, ../c)); // 绝对路径
console.log(path.extname(file.tar.gz)); // .gz6.2 fs文件系统同步/回调/Promise
// Promise API推荐node 14
import { readFile, writeFile, mkdir } from node:fs/promises;
import path from node:path;const p path.join(process.cwd(), data.txt);
await writeFile(p, hello\n, { flag: a });
const content await readFile(p, utf-8);
console.log(content);6.3 os系统信息
import os from node:os;
console.log(os.platform(), os.cpus().length, os.totalmem());6.4 urlURL 与文件路径互转
import { URL, fileURLToPath } from node:url;
const u new URL(https://example.com?a1);
console.log(u.searchParams.get(a)); // 16.5 events事件总线
import { EventEmitter } from node:events;
const bus new EventEmitter();
bus.on(tick, (n) console.log(tick, n));
bus.emit(tick, 1);6.6 child_process子进程
import { exec } from node:child_process;
exec(node -v, (err, stdout) console.log(stdout));7. 异步编程回调 → Promise → async/await
7.1 回调风格历史
import { readFile } from node:fs;
readFile(a.txt, utf-8, (err, data) {if (err) return console.error(err);console.log(data);
});7.2 Promise 风格
import { readFile } from node:fs/promises;
readFile(a.txt, utf-8).then(console.log).catch(console.error);7.3 async/await推荐
import { readFile } from node:fs/promises;async function main() {try {const data await readFile(a.txt, utf-8);console.log(data);} catch (e) {console.error(e);}
}
main();7.4 并发与控制
// 同时并发 3 个任务等待全部完成
await Promise.all([fetch(url1), fetch(url2), fetch(url3)
]);// 并发限制自写一个简单限流器
function pLimit(limit){const queue [];let active 0;const next () {active--;if (queue.length) queue.shift()();};return fn (...args) new Promise((res, rej) {const run () {active;fn(...args).then(res, rej).finally(next);};active limit ? run() : queue.push(run);});
}8. 事件循环与微任务/宏任务Node 特性
Node 的队列优先级简化理解
process.nextTick比微任务还早微任务Promise.then/queueMicrotask宏任务timers、I/O、setImmediate
setTimeout(()console.log(timeout)); // 宏任务
setImmediate(()console.log(immediate)); // 宏任务(检查阶段)
Promise.resolve().then(()console.log(micro)); // 微任务
process.nextTick(()console.log(nextTick)); // 最早// 输出nextTick - micro - (timeout/immediate 先后与上下文有关)9. Buffer 与二进制
Buffer 是 Node 操作二进制数据的结构
const buf Buffer.from(abc, utf-8);
console.log(buf, buf.toString(hex));const copy Buffer.alloc(3);
buf.copy(copy);
console.log(copy.toString()); // abc10. Stream流与管道、背压
四类流Readable / Writable / Duplex / Transform
import { createReadStream, createWriteStream } from node:fs;
const rs createReadStream(in.txt);
const ws createWriteStream(out.txt);
rs.pipe(ws); // 自动处理背压自定义 Transform
import { Transform } from node:stream;const upper new Transform({transform(chunk, enc, cb){cb(null, chunk.toString().toUpperCase());}
});
process.stdin.pipe(upper).pipe(process.stdout);11. HTTP原生 http 模块
11.1 最小 HTTP 服务
import http from node:http;const server http.createServer((req,res){res.writeHead(200, {Content-Type:application/json});res.end(JSON.stringify({ ok:1, path:req.url }));
});server.listen(3000, ()console.log(http://localhost:3000));11.2 路由与 JSON 解析最简
import http from node:http;const server http.createServer(async (req,res){if (req.methodPOST req.url/echo){let body;for await (const chunk of req) body chunk;res.setHeader(Content-Type,application/json);return res.end(JSON.stringify({ body: JSON.parse(body) }));}res.statusCode 404;res.end(Not Found);
});server.listen(3000);12. 使用 Express 快速开发
npm init -y
npm i express// app.js (CommonJS 例)
const express require(express);
const app express();
app.use(express.json());app.get(/ping, (req,res)res.json({pong:1}));
app.post(/echo, (req,res)res.json(req.body));app.listen(3000, ()console.log(http://localhost:3000));ESM 写法
// package.json - type:module
import express from express;
const app express();
app.use(express.json());
app.get(/ping, (req,res)res.json({pong:1}));
app.listen(3000);13. 环境变量与配置
使用 process.env 读取推荐 .env 与 dotenv
npm i dotenvimport dotenv/config;
console.log(process.env.DB_HOST);.env:
DB_HOSTlocalhost
DB_USERroot14. 调试、热重载、脚手架
调试VS Code 中直接“Run and Debug” → Node.js热重载npm i -D nodemonpackage.json:
scripts: {dev: nodemon app.js
}脚手架/工具ts-node、tsx、vite-node进阶15. 实战小项目骨架
15.1 原生 http 版项目结构
my-http/
├─ package.json
├─ app.js
└─ lib/└─ router.jspackage.json
{name: my-http,type: module,version: 1.0.0,scripts: { start: node app.js }
}lib/router.js
export async function handle(req, res) {if (req.method GET req.url /ping) {res.writeHead(200, {Content-Type:application/json});return res.end(JSON.stringify({ pong:1 }));}res.statusCode 404; res.end(Not Found);
}app.js
import http from node:http;
import { handle } from ./lib/router.js;http.createServer(handle).listen(3000, ()console.log(http://localhost:3000));15.2 Express 版项目结构
my-express/
├─ package.json
└─ app.jspackage.json
{name: my-express,version: 1.0.0,scripts: { dev: nodemon app.js, start: node app.js },dependencies: { express: ^4.19.0 },devDependencies: { nodemon: ^3.0.0 }
}app.js
const express require(express);
const app express();
app.use(express.json());app.get(/users/:id, (req,res)res.json({ id:req.params.id }));
app.post(/users, (req,res)res.status(201).json(req.body));app.use((err,req,res,next){console.error(err); res.status(500).json({ message:server error });
});app.listen(3000, ()console.log(http://localhost:3000));16. 常见错误与最佳实践
明确模块体系CJS vs ESM不要混用不清。Node 18 推荐 ESM文件/网络 I/O 一律用 Promise/async注意事件循环优先级process.nextTick 仅用于兼容/必要场景慎用使用 fs/promises 与流大文件错误处理try/catch、Express 中用错误中间件生产建议使用 PM2/容器编排日志落地到文件winston/pino安全避免 eval校验输入使用 HelmetExpress等中间件附常用代码速查
package.jsonCJS
{name: demo,version: 1.0.0,main: app.js,scripts: { start: node app.js }
}package.jsonESM
{name: demo,version: 1.0.0,type: module,scripts: { start: node app.js }
}顶层 awaitESM
// app.mjs or type:module
import { readFile } from node:fs/promises;
const txt await readFile(a.txt,utf-8);
console.log(txt);推荐学习顺序
安装与运行、REPL → 模块体系CJS/ESMfs/path/os/url/events 等常用模块 → 异步编程Promise/async事件循环 → Buffer/Stream → HTTP/Express环境变量/调试 → 小项目实战 → 最佳实践与部署