无需 import/require 直接可用的全局对象,按形态分三类 + CJS 伪全局。多数自 Node 18/20 起对齐 Web 标准全局可用;标注版本表示最低要求。

1. 函数类

定时器

const t = setTimeout(() => console.log("100ms 后执行"), 100);
clearTimeout(t);                          // 取消
 
const iv = setInterval(() => console.log("每 1s"), 1000);
clearInterval(iv);
 
// Node 特有:在 I/O 回调后、下一轮事件循环前立即执行
const im = setImmediate(() => console.log("immediate"));
clearImmediate(im);

queueMicrotask — 手动排入微任务队列

queueMicrotask(() => console.log("微任务,先于 setTimeout 执行"));

atob / btoa — Base64 编解码(字符串,二进制数据用 Buffer)

btoa("hello");        // "aGVsbG8="
atob("aGVsbG8=");     // "hello"

fetch — HTTP 客户端(Node 18+,undici 实现)

const res = await fetch("https://api.example.com/users");
const data = await res.json();

structuredClone — 深拷贝(可处理循环引用,比 JSON 往返保真)

const copy = structuredClone({ a: { b: 1 }, d: new Date() });

reportError — 上报未捕获错误(Node 24+,实验性)

reportError(new Error("手动上报"));   // 走 uncaughtException 处理链

2. 对象类

console — 日志输出

console.log("普通"); 
console.error("错误");
console.table([{ name: "a", v: 1 }]);
console.time("t"); 
console.timeEnd("t");

process — 进程信息与控制

process.env.HOME;             // 环境变量
process.argv;                 // 命令行参数
process.exit(1);              // 退出
process.on("exit", () => {}); // 事件

globalThis — 全局对象本身(跨环境统一写法)

globalThis === global;        // true,Node 中两者同义
globalThis.myFlag = true;     // 挂全局

performance — 高精度计时(Performance API,见 promise 第 6 节测耗时用法)

const t0 = performance.now();      // 微秒级精度,不受系统时钟调整影响
// ...耗时操作
console.log(performance.now() - t0, "ms");
performance.timeOrigin;            // 进程启动时间戳
navigator.userAgent;   // "Node.js/22"
navigator.hardwareConcurrency;   // CPU 核心数

crypto — WebCrypto 全局(Node 19+)

const uuid = crypto.randomUUID();
await crypto.subtle.digest("SHA-256", new TextEncoder().encode("hi"));

3. 构造器 / 类

Buffer — 二进制数据

Buffer.from("hello", "utf8");      // 字符串 → 字节
buf.toString("hex");               // 字节 → hex

URL / URLSearchParams — 标准 URL 解析

const u = new URL("https://a.com/p?x=1&y=2");
u.pathname;                          // "/p"
u.searchParams.get("x");             // "1"

TextEncoder / TextDecoder — UTF-8 字符串 ⇄ 字节

const bytes = new TextEncoder().encode("中文");   // Uint8Array
new TextDecoder().decode(bytes);                  // "中文"

AbortController / AbortSignal — 取消信号(配合 fetch、定时器)

const ac = new AbortController();
setTimeout(() => ac.abort(), 3000);                        // 3s 超时
await fetch("https://slow.example.com", { signal: ac.signal });

Event / EventTarget / CustomEvent — 标准事件系统

const target = new EventTarget();
target.addEventListener("go", (e) => console.log(e.detail));
target.dispatchEvent(new CustomEvent("go", { detail: 42 }));

MessageChannel / MessagePort — 线程/进程间双向消息

const { port1, port2 } = new MessageChannel();
port1.onmessage = (e) => console.log(e.data);
port2.postMessage("hi");            // Worker 场景:把 port2 传给 worker

BroadcastChannel — 同名频道广播(跨 worker)

const bc = new BroadcastChannel("sync");
bc.onmessage = (e) => console.log(e.data);
bc.postMessage("广播给同名频道");

Blob — 不可变二进制大对象

const blob = new Blob(["hello"], { type: "text/plain" });
await blob.text();                  // "hello"

FormData — 表单数据(multipart 请求体)

const fd = new FormData();
fd.append("name", "alice");
await fetch(url, { method: "POST", body: fd });

Headers / Request / Response — Fetch API 三件套

const req = new Request("https://a.com", { headers: { "X-Id": "1" } });
const res = new Response(JSON.stringify({ ok: true }), { status: 200 });
await res.json();                   // { ok: true }

WebSocket — 原生 WebSocket 客户端(Node 22+,稳定)

const ws = new WebSocket("wss://echo.example.com");
ws.onmessage = (e) => console.log(e.data);

CompressionStream / DecompressionStream — 流式压缩(Node 18+)

const gz = stream.pipeThrough(new CompressionStream("gzip"));

DOMException — Web 标准错误类型(Abort 抛出的就是它)

try { await fetch(url, { signal }); }
catch (e) { e instanceof DOMException; /* AbortError 时 true */ }

4. CJS 模块级伪全局(仅 CommonJS,每个文件各有一份,非真全局)

__dirname;        // 当前文件目录
__filename;       // 当前文件路径
require("./x");   // 同步加载模块
module;           // 当前模块对象
exports;          // module.exports 的引用
// ESM 等价写法:
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);

要点速记

  1. 真全局 ≈ 12 个函数 + 6 个对象 + 30 余个构造器,绝大多数对齐 Web 标准
  2. fetch/WebSocket/FormData 等 Web 全局逐步内置,减少对 node-fetch/ws 的依赖
  3. setImmediate/Buffer/process 是 Node 特有,Web 没有
  4. __dirname/require 等只在 CJS 文件内可见,ESM 需用 import.meta 替代