require(id)


  • id <string> 模块名称或路径
  • 返回:<any> 导出的模块内容

用于导入模块、JSON 和本地文件。模块可以从 node_modules 中导入。本地模块和 JSON 文件可以使用相对路径导入(例如 ././foo./bar/baz../foo),这些路径将相对于 __dirname 所指定的目录(如果已定义)或当前工作目录进行解析。POSIX 风格的相对路径以操作系统无关的方式解析,这意味着上述示例在 Windows 上的工作方式与在 Unix 系统上完全相同。

【Used to import modules, JSON, and local files. Modules can be imported from node_modules. Local modules and JSON files can be imported using a relative path (e.g. ./, ./foo, ./bar/baz, ../foo) that will be resolved against the directory named by __dirname (if defined) or the current working directory. The relative paths of POSIX style are resolved in an OS independent fashion, meaning that the examples above will work on Windows in the same way they would on Unix systems.】

// Importing a local module with a path relative to the `__dirname` or current
// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
const myLocalModule = require('./path/myLocalModule');

// Importing a JSON file:
const jsonData = require('./path/filename.json');

// Importing a module from node_modules or Node.js built-in module:
const crypto = require('node:crypto');