首页技术栈归档照片墙音乐日记随想收藏夹友链留言关于

Node.js 基础入门

写作时间:2026-07-08

Node.js 基础入门

概述

Node.js 是基于 Chrome V8 引擎的 JavaScript 运行时,让 JS 可以在服务端运行。

核心特点:

  • 事件驱动:基于 libuv 实现事件循环
  • 非阻塞 I/O:所有 I/O 操作异步执行
  • 单线程:通过事件循环+回调实现高并发
  • NPM:全球最大包管理生态

模块系统

CommonJS

// 导出
module.exports = { add, subtract };
// 导入
const math = require('./math');

ES Modules

export const add = (a, b) => a + b;
import { add } from './math.js';

内置模块

fs 文件系统

const fs = require('fs');
// 异步读取(推荐)
fs.readFile('file.txt', 'utf-8', (err, data) => {
  if (err) throw err;
  console.log(data);
});
// Promise 方式(Node 16+)
import { readFile } from 'fs/promises';
const content = await readFile('file.txt', 'utf-8');

http 模块

const http = require('http');
const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Node.js');
});
server.listen(3000);

事件循环

Node.js 事件循环分为 6 个阶段:

  1. timers:执行 setTimeout/setInterval
  2. pending callbacks:延迟的 I/O 回调
  3. idle, prepare:内部使用
  4. poll:检索新的 I/O 事件
  5. check:执行 setImmediate 回调
  6. close callbacks:关闭回调
setTimeout(() => console.log('timeout'), 0);
setImmediate(() => console.log('immediate'));

NPM 包管理

npm init -y
npm install express        # 运行时依赖
npm install --save-dev jest # 开发依赖

package.json 核心字段:

{
  "name": "my-app",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js"
  }
}
avatar

yuanyourdomain

写代码,做研究,记录生活。

RECOMMENDED

MyBatis 动态 SQL

2026-07-08

Nginx 基础入门

2026-07-08

Maven 多模块与私服

2026-07-08