一、Node.js 内置模块(Module)

Node.js 内置模块是 Node.js 的顶层API,提供给了拜访网络、操作文件等外围性能,npm 外面的模块库就是基于这些顶层 API 的进一步封装,实现更便捷的性能。

1、查看内置模块

创立 example.js 文件,复制上面代码到文件,终端运行 node example.js ,就能够看到 Node.js 内置的所有模块名。

// example.jsconst m = require('module');console.log("\r\n\r\n************************");console.log("require('module') :", m);const builtin = m.builtinModules;console.log("\r\n\r\n************************");console.log("builtin :", builtin);

2、内置模块能够被批改,但不能新增和删除

用内置模块 fs 作为测试对象,通过批改、删除、新增其内容,之后进行同步,最初用动静导入的形式,导入新的 fs ,进行前后比照。查看形式:创立 example.js 文件,复制上面内容到文件,终端运行 node example.js 看后果,如果 assert 的断言有谬误,会抛出谬误,否则没有任何输入。

// example.jsconst fs = require('fs');const assert = require('assert');const { syncBuiltinESMExports } = require('module');function newAPI() {  // ...}// 批改fs.readFile = newAPI;// 删除delete fs.readFileSync;// 新增fs.newAPI = newAPI;// 同步syncBuiltinESMExports();import('fs').then((esmFS) => {  // 批改的内容被同步了  assert.strictEqual(esmFS.readFile, newAPI);    // 删除操作的确胜利了  assert.strictEqual('readFileSync' in fs, false);    // 删除的内容,在新的模块中仍然存在  assert.strictEqual('readFileSync' in esmFS, true);    // 新增内容,在新模块中不存在  assert.strictEqual(esmFS.newAPI, undefined);});

二、参考文档
  • Node.js的内置模块阐明!