Skip to content

内置模块

查看内置模块

NodeJS 内置了一些模块,我们可以直接使用,不需要安装。

通过以下命令查看 NodeJS 内置的模块(笔者 Node 版本是 22):

js
// buildInModules.js
import buildInModules from 'module'
console.log(buildInModules)
shell
node ./buildInModules.js

输出结果如下:

shell
[
    '_http_agent',         '_http_client',        '_http_common',
    '_http_incoming',      '_http_outgoing',      '_http_server',
    '_stream_duplex',      '_stream_passthrough', '_stream_readable',
    '_stream_transform',   '_stream_wrap',        '_stream_writable',
    '_tls_common',         '_tls_wrap',           'assert',
    'assert/strict',       'async_hooks',         'buffer',
    'child_process',       'cluster',             'console',
    'constants',           'crypto',              'dgram',
    'diagnostics_channel', 'dns',                 'dns/promises',
    'domain',              'events',              'fs',
    'fs/promises',         'http',                'http2',
    'https',               'inspector',           'inspector/promises',
    'module',              'net',                 'os',
    'path',                'path/posix',          'path/win32',
    'perf_hooks',          'process',             'punycode',
    'querystring',         'readline',            'readline/promises',
    'repl',                'stream',              'stream/consumers',
    'stream/promises',     'stream/web',          'string_decoder',
    'sys',                 'timers',              'timers/promises',
    'tls',                 'trace_events',        'tty',
    'url',                 'util',                'util/types',
    'v8',                  'vm',                  'wasi',
    'worker_threads',      'zlib'
  ]

以上模块使用的时候直接 requireimport 即可。

看起来有点多,不过平时开发常用的模块就那么几个,熟能生巧。

常用内置模块

path

path 模块是 NodeJS 中用于处理文件路径的内置模块,它提供了一系列的方法,用于解析、拼接、规范化文件路径等。

WARNING

系统中的每个文件都有一个路径。在 Linux 和 macOS 系统上,路径可能看起来像: /users/joe/file.txt ,而 Windows 计算机则有所不同,其路径结构如下: C:\users\joe\file.txt

一种是使用正斜杠 / ,另一种是使用反斜杠 \

因此使用 path 模块时,你需要注意并考虑到这种差异!

从文件路径中提取信息

给定一条路径,使用这些方法可以从中提取信息:

  • dirname :获取文件的父文件夹
  • basename :获取文件名部分
  • extname :获取文件扩展名
js
import path from 'path'

const notes = '/users/joe/notes.txt'

path.dirname(notes) // /users/joe
path.basename(notes) // notes.txt
path.extname(notes) // .txt

通过为 basename 指定第二个参数,你可以获取不带扩展名的文件名:

js
path.basename(notes, path.extname(notes)) // notes

处理路径

  • join :使用平台特定的分隔符将所有给定的路径片段连接在一起
  • resolve :将一系列路径或路径片段解析为绝对路径
  • normalize :规范化给定的路径,并解析 '..''.' 片段
js
import path from 'path'

const name = 'joe'
path.join('/', 'users', name, 'notes.txt') // '/users/joe/notes.txt'

path.resolve('notes.txt') // '/xx/xx/.../notes.txt' (系统中notes.txt文件的绝对路径)

// 在这种情况下,Node.js 会直接将“ /joe.txt ”附加到当前工作目录。如果你指定了第二个参数“folder”,“ resolve ”将会把第一个参数作为第二个参数的基础来使用:
path.resolve('tmp', 'notes.txt') // '/xx/xx/.../tmp/notes.txt'

// 如果第一个参数以斜杠开头,那就意味着它是一个绝对路径:
path.resolve('/etc', 'notes.txt') // '/etc/notes.txt'

path.normalize('/users/joe/..//test.txt') // '/users/test.txt'

无论是 resolve 还是 normalize 都不会检查路径是否存在,它们只是根据所获取的信息来计算出一个路径。

fs

fs 模块是 NodeJS 中最常用的内置模块之一,它提供了一系列的文件操作方法,包括读取文件、写入文件、删除文件、创建目录等。

  • readFile :读取文件内容
  • writeFile :写入文件内容
  • unlink :删除文件
  • mkdir :创建目录
  • readdir :读取目录中的文件和子目录
  • stat :获取文件或目录的状态信息
  • ......

Node.js 中所有文件系统操作都有同步和异步形式,以 fs.readFile 为例:

同步方法

同步方法会阻塞线程,直到文件内容准备就绪。

js
import fs from 'fs'
const data = fs.readFileSync('notes.txt', 'utf-8')
console.log(data)

异步方法

异步形式总是以回调函数作为最后一个参数,回调函数会在文件内容准备就绪后调用,回调函数的第一个参数始终预留用于异常处理,如果没有错误,则为nullundefined

js
import fs from 'fs'
fs.readFile('notes.txt', 'utf-8', (err, data) => {
  if (err) {
    console.log(err)
  } else {
    console.log(data)
  }
})

promise 方法

说到异步方法,自然就会想到 promise,Node.js 也提供了对应的 promise 方法。

js
import fs from 'fs/promises' // 注意这里是 fs/promises

async function readFile(path) {
  try {
    const data = await fs.readFile(path, 'utf-8')
    console.log(data)
  } catch (error) {
    console.log(error)
  }
}

readFile('notes.txt')

看起来优雅多了,也避免了回调地狱。

文件系统标志

文件系统标志是一个可选参数,用于指定文件操作的模式。

标志描述
a打开文件进行追加。如果文件不存在,则创建文件。
ax类似于 a 标志,但如果文件已存在,则会抛出错误。
a+打开文件进行读取和追加。如果文件不存在,则创建文件。
ax+类似于 a+ 标志,但如果文件已存在,则会抛出错误。
as打开文件进行同步写入。如果文件不存在,则创建文件。
as+打开文件进行同步读取和写入。如果文件不存在,则创建文件。
r打开文件进行读取。如果文件不存在,则会抛出错误。
r+打开文件进行读取和写入。如果文件不存在,则会抛出错误。
rs+打开文件进行同步读取和写入。指示操作系统绕过本地文件系统缓存。
w打开文件进行写入。如果文件不存在,则创建文件。如果文件已存在,则会截断文件。
wx类似于 w 标志,但如果文件已存在,则会抛出错误。
w+打开文件进行读取和写入。如果文件不存在,则创建文件。如果文件已存在,则会截断文件。
wx+类似于 w+ 标志,但如果文件已存在,则会抛出错误。

http

http 模块是 NodeJS 中最常用的内置模块之一,它提供了一系列的 HTTP 服务器和客户端方法,包括创建服务器、发送请求、处理响应等。

  • createServer :创建 HTTP 服务器
  • request :发送 HTTP 请求
  • get :发送 GET 请求
  • post :发送 POST 请求
  • put :发送 PUT 请求
  • delete :发送 DELETE 请求
  • patch :发送 PATCH 请求
  • head :发送 HEAD 请求
  • options :发送 OPTIONS 请求

创建服务器

创建 HTTP 服务器的方法如下:

js
import http from 'http'
const server = http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/plain' })
  res.end('Hello World\n')
})
server.listen(8080, () => {
  console.log('Server running at http://127.0.0.1:8080/')
})

关于 http 模块的更多细节,我们会在后面的章节中,进行详细介绍。