node.js 零基础入门

发布于:2025-08-10 ⋅ 阅读:(16) ⋅ 点赞:(0)

Node.js 零 基础入门与核心语法

适用对象:完全没接触过 Node.js 的同学
目标:从 0 到能写 CLI、小型 HTTP 服务、文件脚本、调用系统/网络资源

目录

  1. 什么是 Node.js
  2. 安装与运行
  3. 运行脚本与 REPL
  4. 模块体系:CommonJS 与 ES Modules
  5. 基础语法在 Node 环境下的差异与全局对象
  6. 内置核心模块概览与常用模块
  7. 异步编程:回调 → Promise → async/await
  8. 事件循环与微任务/宏任务(Node 特性)
  9. Buffer 与二进制
  10. Stream(流)与管道、背压
  11. HTTP:原生 http 模块
  12. 使用 Express 快速开发
  13. 环境变量与配置
  14. 调试、热重载、脚手架
  15. 实战:小项目骨架(原生与 Express)
  16. 常见错误与最佳实践

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
  • 交互式 REPL:node 回车后直接执行表达式
// app.js
console.log('Hello Node');

4. 模块体系:CommonJS 与 ES Modules

Node 支持两种模块系统。

A) CommonJS(CJS)默认

  • 文件后缀通常 .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 Modules(ESM)

  • 在 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'));     // .gz

6.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 url:URL 与文件路径互转

import { URL, fileURLToPath } from 'node:url';
const u = new URL('https://example.com?a=1');
console.log(u.searchParams.get('a')); // 1

6.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()); // 'abc'

10. 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.method==='POST' && 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 读取
  • 推荐 .envdotenv
npm i dotenv
import 'dotenv/config';
console.log(process.env.DB_HOST);

.env:

DB_HOST=localhost
DB_USER=root

14. 调试、热重载、脚手架

  • 调试:VS Code 中直接“Run and Debug” → Node.js
  • 热重载:npm i -D nodemon,package.json:
"scripts": {
  "dev": "nodemon app.js"
}
  • 脚手架/工具:ts-node、tsx、vite-node(进阶)

15. 实战:小项目骨架

15.1 原生 http 版项目结构

my-http/
├─ package.json
├─ app.js
└─ lib/
   └─ router.js

package.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.js

package.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,校验输入,使用 Helmet(Express)等中间件

附:常用代码速查

package.json(CJS)

{
  "name": "demo",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": { "start": "node app.js" }
}

package.json(ESM)

{
  "name": "demo",
  "version": "1.0.0",
  "type": "module",
  "scripts": { "start": "node app.js" }
}

顶层 await(ESM)

// app.mjs or "type":"module"
import { readFile } from 'node:fs/promises';
const txt = await readFile('a.txt','utf-8');
console.log(txt);

推荐学习顺序

  1. 安装与运行、REPL → 模块体系(CJS/ESM)
  2. fs/path/os/url/events 等常用模块 → 异步编程(Promise/async)
  3. 事件循环 → Buffer/Stream → HTTP/Express
  4. 环境变量/调试 → 小项目实战 → 最佳实践与部署


网站公告

今日签到

点亮在社区的每一天
去签到