2020-08-07 10:40:45 +02:00
|
|
|
# Modules: CommonJS modules
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2017-01-22 19:16:21 -08:00
|
|
|
<!--introduced_in=v0.10.0-->
|
|
|
|
|
2017-03-02 10:35:24 -08:00
|
|
|
> Stability: 2 - Stable
|
2012-03-02 15:14:03 -08:00
|
|
|
|
2012-02-27 11:09:34 -08:00
|
|
|
<!--name=module-->
|
2010-10-28 23:18:16 +11:00
|
|
|
|
2022-04-02 20:29:22 +02:00
|
|
|
CommonJS modules are the original way to package JavaScript code for Node.js.
|
|
|
|
Node.js also supports the [ECMAScript modules][] standard used by browsers
|
|
|
|
and other JavaScript runtimes.
|
|
|
|
|
|
|
|
In Node.js, each file is treated as a separate module. For
|
2017-12-04 23:47:39 -08:00
|
|
|
example, consider a file named `foo.js`:
|
2010-10-28 23:18:16 +11:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
|
|
|
const circle = require('./circle.js');
|
2016-07-26 22:25:08 -04:00
|
|
|
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
|
2016-01-17 18:39:07 +01:00
|
|
|
```
|
2010-10-28 23:18:16 +11:00
|
|
|
|
2016-11-27 11:16:38 -08:00
|
|
|
On the first line, `foo.js` loads the module `circle.js` that is in the same
|
|
|
|
directory as `foo.js`.
|
|
|
|
|
|
|
|
Here are the contents of `circle.js`:
|
2010-10-28 23:18:16 +11:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
2017-04-05 04:16:56 +03:00
|
|
|
const { PI } = Math;
|
2010-10-28 23:18:16 +11:00
|
|
|
|
2017-04-05 04:16:56 +03:00
|
|
|
exports.area = (r) => PI * r ** 2;
|
2016-01-24 11:15:51 +02:00
|
|
|
|
|
|
|
exports.circumference = (r) => 2 * PI * r;
|
2016-01-17 18:39:07 +01:00
|
|
|
```
|
2010-10-28 23:18:16 +11:00
|
|
|
|
|
|
|
The module `circle.js` has exported the functions `area()` and
|
2017-04-26 10:16:12 -07:00
|
|
|
`circumference()`. Functions and objects are added to the root of a module
|
|
|
|
by specifying additional properties on the special `exports` object.
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2016-04-27 23:41:41 +01:00
|
|
|
Variables local to the module will be private, because the module is wrapped
|
2021-07-04 20:39:17 -07:00
|
|
|
in a function by Node.js (see [module wrapper](#the-module-wrapper)).
|
2016-04-27 23:41:41 +01:00
|
|
|
In this example, the variable `PI` is private to `circle.js`.
|
2013-04-08 09:59:15 -07:00
|
|
|
|
2017-04-26 10:16:12 -07:00
|
|
|
The `module.exports` property can be assigned a new value (such as a function
|
|
|
|
or object).
|
2013-10-25 22:03:02 -07:00
|
|
|
|
2024-04-03 13:21:28 -07:00
|
|
|
In the following code, `bar.js` makes use of the `square` module, which exports
|
|
|
|
a Square class:
|
2013-04-08 09:59:15 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
2017-11-27 18:01:56 -08:00
|
|
|
const Square = require('./square.js');
|
|
|
|
const mySquare = new Square(2);
|
|
|
|
console.log(`The area of mySquare is ${mySquare.area()}`);
|
2016-01-17 18:39:07 +01:00
|
|
|
```
|
2013-04-08 09:59:15 -07:00
|
|
|
|
2013-10-25 22:03:02 -07:00
|
|
|
The `square` module is defined in `square.js`:
|
2013-04-08 09:59:15 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
2018-12-03 17:15:45 +01:00
|
|
|
// Assigning to exports will not modify module, must use module.exports
|
2017-12-09 13:27:31 -05:00
|
|
|
module.exports = class Square {
|
|
|
|
constructor(width) {
|
|
|
|
this.width = width;
|
|
|
|
}
|
|
|
|
|
|
|
|
area() {
|
|
|
|
return this.width ** 2;
|
|
|
|
}
|
2017-04-05 04:16:56 +03:00
|
|
|
};
|
2016-01-17 18:39:07 +01:00
|
|
|
```
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2022-01-17 11:36:19 +01:00
|
|
|
The CommonJS module system is implemented in the [`module` core module][].
|
|
|
|
|
|
|
|
## Enabling
|
|
|
|
|
|
|
|
<!-- type=misc -->
|
|
|
|
|
|
|
|
Node.js has two module systems: CommonJS modules and [ECMAScript modules][].
|
|
|
|
|
|
|
|
By default, Node.js will treat the following as CommonJS modules:
|
|
|
|
|
|
|
|
* Files with a `.cjs` extension;
|
|
|
|
|
|
|
|
* Files with a `.js` extension when the nearest parent `package.json` file
|
|
|
|
contains a top-level field [`"type"`][] with a value of `"commonjs"`.
|
|
|
|
|
2023-10-20 08:44:56 -07:00
|
|
|
* Files with a `.js` extension or without an extension, when the nearest parent
|
|
|
|
`package.json` file doesn't contain a top-level field [`"type"`][] or there is
|
|
|
|
no `package.json` in any parent folder; unless the file contains syntax that
|
|
|
|
errors unless it is evaluated as an ES module. Package authors should include
|
2022-01-17 11:36:19 +01:00
|
|
|
the [`"type"`][] field, even in packages where all sources are CommonJS. Being
|
|
|
|
explicit about the `type` of the package will make things easier for build
|
|
|
|
tools and loaders to determine how the files in the package should be
|
|
|
|
interpreted.
|
|
|
|
|
|
|
|
* Files with an extension that is not `.mjs`, `.cjs`, `.json`, `.node`, or `.js`
|
|
|
|
(when the nearest parent `package.json` file contains a top-level field
|
|
|
|
[`"type"`][] with a value of `"module"`, those files will be recognized as
|
2022-11-14 01:01:41 +08:00
|
|
|
CommonJS modules only if they are being included via `require()`, not when
|
|
|
|
used as the command-line entry point of the program).
|
2022-01-17 11:36:19 +01:00
|
|
|
|
|
|
|
See [Determining module system][] for more details.
|
|
|
|
|
|
|
|
Calling `require()` always use the CommonJS module loader. Calling `import()`
|
|
|
|
always use the ECMAScript module loader.
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2015-11-04 12:50:07 -05:00
|
|
|
## Accessing the main module
|
|
|
|
|
|
|
|
<!-- type=misc -->
|
|
|
|
|
|
|
|
When a file is run directly from Node.js, `require.main` is set to its
|
2017-04-26 10:16:12 -07:00
|
|
|
`module`. That means that it is possible to determine whether a file has been
|
|
|
|
run directly by testing `require.main === module`.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
For a file `foo.js`, this will be `true` if run via `node foo.js`, but
|
|
|
|
`false` if run by `require('./foo')`.
|
|
|
|
|
2022-01-05 11:05:25 +01:00
|
|
|
When the entry point is not a CommonJS module, `require.main` is `undefined`,
|
|
|
|
and the main module is out of reach.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2021-07-17 22:25:09 -07:00
|
|
|
## Package manager tips
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
<!-- type=misc -->
|
|
|
|
|
2020-02-09 16:09:36 -10:00
|
|
|
The semantics of the Node.js `require()` function were designed to be general
|
2019-10-23 15:35:13 -07:00
|
|
|
enough to support reasonable directory structures. Package manager programs
|
|
|
|
such as `dpkg`, `rpm`, and `npm` will hopefully find it possible to build
|
|
|
|
native packages from Node.js modules without modification.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2024-04-03 13:21:28 -07:00
|
|
|
In the following, we give a suggested directory structure that could work:
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
Let's say that we wanted to have the folder at
|
|
|
|
`/usr/lib/node/<some-package>/<some-version>` hold the contents of a
|
|
|
|
specific version of a package.
|
|
|
|
|
2017-04-26 10:16:12 -07:00
|
|
|
Packages can depend on one another. In order to install package `foo`, it
|
|
|
|
may be necessary to install a specific version of package `bar`. The `bar`
|
|
|
|
package may itself have dependencies, and in some cases, these may even collide
|
|
|
|
or form cyclic dependencies.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2020-09-09 10:46:32 -07:00
|
|
|
Because Node.js looks up the `realpath` of any modules it loads (that is, it
|
2021-10-30 15:40:34 -07:00
|
|
|
resolves symlinks) and then [looks for their dependencies in `node_modules` folders](#loading-from-node_modules-folders),
|
2020-09-09 10:46:32 -07:00
|
|
|
this situation can be resolved with the following architecture:
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2019-10-23 21:28:42 -07:00
|
|
|
* `/usr/lib/node/foo/1.2.3/`: Contents of the `foo` package, version 1.2.3.
|
|
|
|
* `/usr/lib/node/bar/4.3.2/`: Contents of the `bar` package that `foo` depends
|
|
|
|
on.
|
|
|
|
* `/usr/lib/node/foo/1.2.3/node_modules/bar`: Symbolic link to
|
2015-11-04 12:50:07 -05:00
|
|
|
`/usr/lib/node/bar/4.3.2/`.
|
2019-10-23 21:28:42 -07:00
|
|
|
* `/usr/lib/node/bar/4.3.2/node_modules/*`: Symbolic links to the packages that
|
|
|
|
`bar` depends on.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
Thus, even if a cycle is encountered, or if there are dependency
|
|
|
|
conflicts, every module will be able to get a version of its dependency
|
|
|
|
that it can use.
|
|
|
|
|
|
|
|
When the code in the `foo` package does `require('bar')`, it will get the
|
|
|
|
version that is symlinked into `/usr/lib/node/foo/1.2.3/node_modules/bar`.
|
|
|
|
Then, when the code in the `bar` package calls `require('quux')`, it'll get
|
|
|
|
the version that is symlinked into
|
|
|
|
`/usr/lib/node/bar/4.3.2/node_modules/quux`.
|
|
|
|
|
|
|
|
Furthermore, to make the module lookup process even more optimal, rather
|
|
|
|
than putting packages directly in `/usr/lib/node`, we could put them in
|
2018-04-02 08:38:48 +03:00
|
|
|
`/usr/lib/node_modules/<name>/<version>`. Then Node.js will not bother
|
2015-11-04 12:50:07 -05:00
|
|
|
looking for missing dependencies in `/usr/node_modules` or `/node_modules`.
|
|
|
|
|
|
|
|
In order to make modules available to the Node.js REPL, it might be useful to
|
|
|
|
also add the `/usr/lib/node_modules` folder to the `$NODE_PATH` environment
|
2018-04-02 08:38:48 +03:00
|
|
|
variable. Since the module lookups using `node_modules` folders are all
|
2015-11-04 12:50:07 -05:00
|
|
|
relative, and based on the real path of the files making the calls to
|
|
|
|
`require()`, the packages themselves can be anywhere.
|
|
|
|
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
## Loading ECMAScript modules using `require()`
|
2019-04-25 17:32:04 -04:00
|
|
|
|
2024-09-26 16:21:37 +02:00
|
|
|
<!-- YAML
|
2024-10-02 23:02:31 +02:00
|
|
|
added:
|
|
|
|
- v22.0.0
|
|
|
|
- v20.17.0
|
2024-09-26 16:21:37 +02:00
|
|
|
changes:
|
2024-12-09 15:47:25 +01:00
|
|
|
- version:
|
2024-12-18 22:40:13 +01:00
|
|
|
- v23.5.0
|
2025-01-05 13:33:23 -05:00
|
|
|
- v22.13.0
|
2025-03-06 13:18:40 +01:00
|
|
|
- v20.19.0
|
2024-12-09 15:47:25 +01:00
|
|
|
pr-url: https://github.com/nodejs/node/pull/56194
|
|
|
|
description: This feature no longer emits an experimental warning by default,
|
|
|
|
though the warning can still be emitted by --trace-require-module.
|
2024-11-27 16:58:44 -05:00
|
|
|
- version:
|
|
|
|
- v23.0.0
|
|
|
|
- v22.12.0
|
2025-03-06 13:18:40 +01:00
|
|
|
- v20.19.0
|
2024-09-26 16:21:37 +02:00
|
|
|
pr-url: https://github.com/nodejs/node/pull/55085
|
2024-10-02 23:02:31 +02:00
|
|
|
description: This feature is no longer behind the `--experimental-require-module` CLI flag.
|
2024-11-27 16:58:44 -05:00
|
|
|
- version:
|
|
|
|
- v23.0.0
|
|
|
|
- v22.12.0
|
2024-07-14 13:00:49 -07:00
|
|
|
pr-url: https://github.com/nodejs/node/pull/54563
|
|
|
|
description: Support `'module.exports'` interop export in `require(esm)`.
|
2024-09-26 16:21:37 +02:00
|
|
|
-->
|
|
|
|
|
2024-10-02 23:02:31 +02:00
|
|
|
> Stability: 1.2 - Release candidate
|
|
|
|
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
The `.mjs` extension is reserved for [ECMAScript Modules][].
|
2024-09-26 16:21:37 +02:00
|
|
|
See [Determining module system][] section for more info
|
2022-01-02 18:20:02 +01:00
|
|
|
regarding which files are parsed as ECMAScript modules.
|
2019-04-25 17:32:04 -04:00
|
|
|
|
2024-09-26 16:21:37 +02:00
|
|
|
`require()` only supports loading ECMAScript modules that meet the following requirements:
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
|
2024-04-29 22:21:53 +02:00
|
|
|
* The module is fully synchronous (contains no top-level `await`); and
|
|
|
|
* One of these conditions are met:
|
|
|
|
1. The file has a `.mjs` extension.
|
|
|
|
2. The file has a `.js` extension, and the closest `package.json` contains `"type": "module"`
|
|
|
|
3. The file has a `.js` extension, the closest `package.json` does not contain
|
2024-07-20 11:30:46 -07:00
|
|
|
`"type": "commonjs"`, and the module contains ES module syntax.
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
|
2025-02-16 15:28:33 +00:00
|
|
|
If the ES Module being loaded meets the requirements, `require()` can load it and
|
2025-02-16 12:00:56 +00:00
|
|
|
return the [module namespace object][]. In this case it is similar to dynamic
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
`import()` but is run synchronously and returns the name space object
|
|
|
|
directly.
|
|
|
|
|
2024-03-20 21:41:22 +01:00
|
|
|
With the following ES Modules:
|
|
|
|
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
```mjs
|
2024-03-20 21:41:22 +01:00
|
|
|
// distance.mjs
|
2025-02-16 18:26:30 +00:00
|
|
|
export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); }
|
2024-03-20 21:41:22 +01:00
|
|
|
```
|
|
|
|
|
|
|
|
```mjs
|
|
|
|
// point.mjs
|
2024-07-14 13:00:49 -07:00
|
|
|
export default class Point {
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
constructor(x, y) { this.x = x; this.y = y; }
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2024-09-26 16:21:37 +02:00
|
|
|
A CommonJS module can load them with `require()`:
|
2024-03-20 21:41:22 +01:00
|
|
|
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
```cjs
|
2024-03-20 21:41:22 +01:00
|
|
|
const distance = require('./distance.mjs');
|
|
|
|
console.log(distance);
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
// [Module: null prototype] {
|
|
|
|
// distance: [Function: distance]
|
|
|
|
// }
|
|
|
|
|
2024-03-20 21:41:22 +01:00
|
|
|
const point = require('./point.mjs');
|
|
|
|
console.log(point);
|
|
|
|
// [Module: null prototype] {
|
|
|
|
// default: [class Point],
|
|
|
|
// __esModule: true,
|
|
|
|
// }
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
```
|
|
|
|
|
2024-03-20 21:41:22 +01:00
|
|
|
For interoperability with existing tools that convert ES Modules into CommonJS,
|
|
|
|
which could then load real ES Modules through `require()`, the returned namespace
|
|
|
|
would contain a `__esModule: true` property if it has a `default` export so that
|
|
|
|
consuming code generated by tools can recognize the default exports in real
|
|
|
|
ES Modules. If the namespace already defines `__esModule`, this would not be added.
|
|
|
|
This property is experimental and can change in the future. It should only be used
|
|
|
|
by tools converting ES modules into CommonJS modules, following existing ecosystem
|
|
|
|
conventions. Code authored directly in CommonJS should avoid depending on it.
|
|
|
|
|
2025-02-17 11:50:49 +00:00
|
|
|
When an ES Module contains both named exports and a default export, the result returned by `require()`
|
2025-02-16 12:00:56 +00:00
|
|
|
is the [module namespace object][], which places the default export in the `.default` property, similar to
|
2024-07-14 13:00:49 -07:00
|
|
|
the results returned by `import()`.
|
|
|
|
To customize what should be returned by `require(esm)` directly, the ES Module can export the
|
|
|
|
desired value using the string name `"module.exports"`.
|
|
|
|
|
|
|
|
<!-- eslint-disable @stylistic/js/semi -->
|
|
|
|
|
|
|
|
```mjs
|
|
|
|
// point.mjs
|
|
|
|
export default class Point {
|
|
|
|
constructor(x, y) { this.x = x; this.y = y; }
|
|
|
|
}
|
|
|
|
|
|
|
|
// `distance` is lost to CommonJS consumers of this module, unless it's
|
|
|
|
// added to `Point` as a static property.
|
2025-02-16 18:26:30 +00:00
|
|
|
export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); }
|
2024-07-14 13:00:49 -07:00
|
|
|
export { Point as 'module.exports' }
|
|
|
|
```
|
|
|
|
|
|
|
|
<!-- eslint-disable node-core/no-duplicate-requires -->
|
|
|
|
|
|
|
|
```cjs
|
|
|
|
const Point = require('./point.mjs');
|
|
|
|
console.log(Point); // [class Point]
|
|
|
|
|
|
|
|
// Named exports are lost when 'module.exports' is used
|
|
|
|
const { distance } = require('./point.mjs');
|
|
|
|
console.log(distance); // undefined
|
|
|
|
```
|
|
|
|
|
|
|
|
Notice in the example above, when the `module.exports` export name is used, named exports
|
|
|
|
will be lost to CommonJS consumers. To allow CommonJS consumers to continue accessing
|
|
|
|
named exports, the module can make sure that the default export is an object with the
|
|
|
|
named exports attached to it as properties. For example with the example above,
|
|
|
|
`distance` can be attached to the default export, the `Point` class, as a static method.
|
|
|
|
|
|
|
|
<!-- eslint-disable @stylistic/js/semi -->
|
|
|
|
|
|
|
|
```mjs
|
2025-02-16 18:26:30 +00:00
|
|
|
export function distance(a, b) { return Math.sqrt((b.x - a.x) ** 2 + (b.y - a.y) ** 2); }
|
2024-07-14 13:00:49 -07:00
|
|
|
|
|
|
|
export default class Point {
|
|
|
|
constructor(x, y) { this.x = x; this.y = y; }
|
|
|
|
static distance = distance;
|
|
|
|
}
|
|
|
|
|
|
|
|
export { Point as 'module.exports' }
|
|
|
|
```
|
|
|
|
|
|
|
|
<!-- eslint-disable node-core/no-duplicate-requires -->
|
|
|
|
|
|
|
|
```cjs
|
|
|
|
const Point = require('./point.mjs');
|
|
|
|
console.log(Point); // [class Point]
|
|
|
|
|
|
|
|
const { distance } = require('./point.mjs');
|
|
|
|
console.log(distance); // [Function: distance]
|
|
|
|
```
|
|
|
|
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
If the module being `require()`'d contains top-level `await`, or the module
|
|
|
|
graph it `import`s contains top-level `await`,
|
|
|
|
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users should
|
2024-09-26 16:21:37 +02:00
|
|
|
load the asynchronous module using [`import()`][].
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
|
|
|
|
If `--experimental-print-required-tla` is enabled, instead of throwing
|
|
|
|
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
|
|
|
|
module, try to locate the top-level awaits, and print their location to
|
|
|
|
help users fix them.
|
|
|
|
|
2024-09-26 16:21:37 +02:00
|
|
|
Support for loading ES modules using `require()` is currently
|
|
|
|
experimental and can be disabled using `--no-experimental-require-module`.
|
2024-12-09 15:47:25 +01:00
|
|
|
To print where this feature is used, use [`--trace-require-module`][].
|
|
|
|
|
2024-10-07 17:26:10 +02:00
|
|
|
This feature can be detected by checking if
|
|
|
|
[`process.features.require_module`][] is `true`.
|
2024-09-26 16:21:37 +02:00
|
|
|
|
2022-02-08 09:42:52 -08:00
|
|
|
## All together
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
<!-- type=misc -->
|
|
|
|
|
|
|
|
To get the exact filename that will be loaded when `require()` is called, use
|
|
|
|
the `require.resolve()` function.
|
|
|
|
|
|
|
|
Putting together all of the above, here is the high-level algorithm
|
2019-05-24 16:22:49 +03:00
|
|
|
in pseudocode of what `require()` does:
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2024-07-06 12:06:46 +01:00
|
|
|
```text
|
2016-01-17 18:39:07 +01:00
|
|
|
require(X) from module at path Y
|
|
|
|
1. If X is a core module,
|
|
|
|
a. return the core module
|
|
|
|
b. STOP
|
2017-03-17 08:16:44 -05:00
|
|
|
2. If X begins with '/'
|
2025-02-18 13:13:29 +00:00
|
|
|
a. set Y to the file system root
|
2025-03-22 11:34:29 -05:00
|
|
|
3. If X is equal to '.', or X begins with './', '/' or '../'
|
2016-01-17 18:39:07 +01:00
|
|
|
a. LOAD_AS_FILE(Y + X)
|
|
|
|
b. LOAD_AS_DIRECTORY(Y + X)
|
2019-10-11 16:01:34 -07:00
|
|
|
c. THROW "not found"
|
2020-06-27 22:09:24 -07:00
|
|
|
4. If X begins with '#'
|
2020-08-09 16:54:01 -07:00
|
|
|
a. LOAD_PACKAGE_IMPORTS(X, dirname(Y))
|
|
|
|
5. LOAD_PACKAGE_SELF(X, dirname(Y))
|
|
|
|
6. LOAD_NODE_MODULES(X, dirname(Y))
|
|
|
|
7. THROW "not found"
|
2016-01-17 18:39:07 +01:00
|
|
|
|
2024-04-29 22:21:53 +02:00
|
|
|
MAYBE_DETECT_AND_LOAD(X)
|
|
|
|
1. If X parses as a CommonJS module, load X as a CommonJS module. STOP.
|
2024-09-26 16:21:37 +02:00
|
|
|
2. Else, if the source code of X can be parsed as ECMAScript module using
|
2024-04-29 22:21:53 +02:00
|
|
|
<a href="esm.md#resolver-algorithm-specification">DETECT_MODULE_SYNTAX defined in
|
|
|
|
the ESM resolver</a>,
|
|
|
|
a. Load X as an ECMAScript module. STOP.
|
|
|
|
3. THROW the SyntaxError from attempting to parse X as CommonJS in 1. STOP.
|
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
LOAD_AS_FILE(X)
|
2020-06-20 16:46:33 -07:00
|
|
|
1. If X is a file, load X as its file extension format. STOP
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
2. If X.js is a file,
|
|
|
|
a. Find the closest package scope SCOPE to X.
|
2024-04-29 22:21:53 +02:00
|
|
|
b. If no scope was found
|
|
|
|
1. MAYBE_DETECT_AND_LOAD(X.js)
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
c. If the SCOPE/package.json contains "type" field,
|
|
|
|
1. If the "type" field is "module", load X.js as an ECMAScript module. STOP.
|
2025-02-17 11:50:49 +00:00
|
|
|
2. If the "type" field is "commonjs", load X.js as a CommonJS module. STOP.
|
2024-04-29 22:21:53 +02:00
|
|
|
d. MAYBE_DETECT_AND_LOAD(X.js)
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
3. If X.json is a file, load X.json to a JavaScript Object. STOP
|
2020-06-20 16:46:33 -07:00
|
|
|
4. If X.node is a file, load X.node as binary addon. STOP
|
2016-01-17 18:39:07 +01:00
|
|
|
|
2017-02-27 12:01:18 -06:00
|
|
|
LOAD_INDEX(X)
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
1. If X/index.js is a file
|
|
|
|
a. Find the closest package scope SCOPE to X.
|
|
|
|
b. If no scope was found, load X/index.js as a CommonJS module. STOP.
|
|
|
|
c. If the SCOPE/package.json contains "type" field,
|
|
|
|
1. If the "type" field is "module", load X/index.js as an ECMAScript module. STOP.
|
2025-02-17 11:50:49 +00:00
|
|
|
2. Else, load X/index.js as a CommonJS module. STOP.
|
2017-02-27 12:01:18 -06:00
|
|
|
2. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
|
2020-06-20 16:46:33 -07:00
|
|
|
3. If X/index.node is a file, load X/index.node as binary addon. STOP
|
2017-02-27 12:01:18 -06:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
LOAD_AS_DIRECTORY(X)
|
|
|
|
1. If X/package.json is a file,
|
|
|
|
a. Parse X/package.json, and look for "main" field.
|
2019-03-20 17:00:57 +01:00
|
|
|
b. If "main" is a falsy value, GOTO 2.
|
|
|
|
c. let M = X + (json main field)
|
|
|
|
d. LOAD_AS_FILE(M)
|
|
|
|
e. LOAD_INDEX(M)
|
|
|
|
f. LOAD_INDEX(X) DEPRECATED
|
|
|
|
g. THROW "not found"
|
2017-02-27 12:01:18 -06:00
|
|
|
2. LOAD_INDEX(X)
|
2016-01-17 18:39:07 +01:00
|
|
|
|
|
|
|
LOAD_NODE_MODULES(X, START)
|
2018-05-05 01:43:12 -04:00
|
|
|
1. let DIRS = NODE_MODULES_PATHS(START)
|
2016-01-17 18:39:07 +01:00
|
|
|
2. for each DIR in DIRS:
|
2020-08-09 16:54:01 -07:00
|
|
|
a. LOAD_PACKAGE_EXPORTS(X, DIR)
|
2020-03-19 01:49:49 +02:00
|
|
|
b. LOAD_AS_FILE(DIR/X)
|
|
|
|
c. LOAD_AS_DIRECTORY(DIR/X)
|
2016-01-17 18:39:07 +01:00
|
|
|
|
|
|
|
NODE_MODULES_PATHS(START)
|
|
|
|
1. let PARTS = path split(START)
|
|
|
|
2. let I = count of PARTS - 1
|
2021-12-15 02:51:24 +08:00
|
|
|
3. let DIRS = []
|
2016-01-17 18:39:07 +01:00
|
|
|
4. while I >= 0,
|
2024-09-27 23:34:38 +08:00
|
|
|
a. if PARTS[I] = "node_modules", GOTO d.
|
2016-11-12 16:18:05 +09:00
|
|
|
b. DIR = path join(PARTS[0 .. I] + "node_modules")
|
2021-12-15 02:51:24 +08:00
|
|
|
c. DIRS = DIR + DIRS
|
2016-11-12 16:18:05 +09:00
|
|
|
d. let I = I - 1
|
2021-12-15 02:51:24 +08:00
|
|
|
5. return DIRS + GLOBAL_FOLDERS
|
2019-08-19 20:59:25 -07:00
|
|
|
|
2020-08-09 16:54:01 -07:00
|
|
|
LOAD_PACKAGE_IMPORTS(X, DIR)
|
|
|
|
1. Find the closest package scope SCOPE to DIR.
|
2019-12-17 01:58:19 -05:00
|
|
|
2. If no scope was found, return.
|
2020-08-09 16:54:01 -07:00
|
|
|
3. If the SCOPE/package.json "imports" is null or undefined, return.
|
module: implement the "module-sync" exports condition
This patch implements a "module-sync" exports condition
for packages to supply a sycnrhonous ES module to the
Node.js module loader, no matter it's being required
or imported. This is similar to the "module" condition
that bundlers have been using to support `require(esm)`
in Node.js, and allows dual-package authors to opt into
ESM-first only newer versions of Node.js that supports
require(esm) while avoiding the dual-package hazard.
```json
{
"type": "module",
"exports": {
"node": {
// On new version of Node.js, both require() and import get
// the ESM version
"module-sync": "./index.js",
// On older version of Node.js, where "module" and
// require(esm) are not supported, use the transpiled CJS version
// to avoid dual-package hazard. Library authors can decide
// to drop support for older versions of Node.js when they think
// it's time.
"default": "./dist/index.cjs"
},
// On any other environment, use the ESM version.
"default": "./index.js"
}
}
```
We end up implementing a condition with a different name
instead of reusing "module", because existing code in the
ecosystem using the "module" condition sometimes also expect
the module resolution for these ESM files to work in CJS
style, which is supported by bundlers, but the native
Node.js loader has intentionally made ESM resolution
different from CJS resolution (e.g. forbidding `import
'./noext'` or `import './directory'`), so it would be
semver-major to implement a `"module"` condition
without implementing the forbidden ESM resolution rules.
For now, this just implments a new condition as semver-minor
so it can be backported to older LTS.
Refs: https://webpack.js.org/guides/package-exports/#target-environment-independent-packages
PR-URL: https://github.com/nodejs/node/pull/54648
Fixes: https://github.com/nodejs/node/issues/52173
Refs: https://github.com/joyeecheung/test-module-condition
Refs: https://github.com/nodejs/node/issues/52697
Reviewed-By: Jacob Smith <jacob@frende.me>
Reviewed-By: Jan Krems <jan.krems@gmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
2024-09-25 08:35:26 +02:00
|
|
|
4. If `--experimental-require-module` is enabled
|
|
|
|
a. let CONDITIONS = ["node", "require", "module-sync"]
|
|
|
|
b. Else, let CONDITIONS = ["node", "require"]
|
|
|
|
5. let MATCH = PACKAGE_IMPORTS_RESOLVE(X, pathToFileURL(SCOPE),
|
|
|
|
CONDITIONS) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
|
|
|
|
6. RESOLVE_ESM_MATCH(MATCH).
|
2019-07-18 21:52:55 -07:00
|
|
|
|
2020-08-09 16:54:01 -07:00
|
|
|
LOAD_PACKAGE_EXPORTS(X, DIR)
|
|
|
|
1. Try to interpret X as a combination of NAME and SUBPATH where the name
|
2019-07-18 21:52:55 -07:00
|
|
|
may have a @scope/ prefix and the subpath begins with a slash (`/`).
|
2020-08-09 16:54:01 -07:00
|
|
|
2. If X does not match this pattern or DIR/NAME/package.json is not a file,
|
2020-03-19 01:49:49 +02:00
|
|
|
return.
|
2020-08-09 16:54:01 -07:00
|
|
|
3. Parse DIR/NAME/package.json, and look for "exports" field.
|
2020-03-19 01:49:49 +02:00
|
|
|
4. If "exports" is null or undefined, return.
|
module: implement the "module-sync" exports condition
This patch implements a "module-sync" exports condition
for packages to supply a sycnrhonous ES module to the
Node.js module loader, no matter it's being required
or imported. This is similar to the "module" condition
that bundlers have been using to support `require(esm)`
in Node.js, and allows dual-package authors to opt into
ESM-first only newer versions of Node.js that supports
require(esm) while avoiding the dual-package hazard.
```json
{
"type": "module",
"exports": {
"node": {
// On new version of Node.js, both require() and import get
// the ESM version
"module-sync": "./index.js",
// On older version of Node.js, where "module" and
// require(esm) are not supported, use the transpiled CJS version
// to avoid dual-package hazard. Library authors can decide
// to drop support for older versions of Node.js when they think
// it's time.
"default": "./dist/index.cjs"
},
// On any other environment, use the ESM version.
"default": "./index.js"
}
}
```
We end up implementing a condition with a different name
instead of reusing "module", because existing code in the
ecosystem using the "module" condition sometimes also expect
the module resolution for these ESM files to work in CJS
style, which is supported by bundlers, but the native
Node.js loader has intentionally made ESM resolution
different from CJS resolution (e.g. forbidding `import
'./noext'` or `import './directory'`), so it would be
semver-major to implement a `"module"` condition
without implementing the forbidden ESM resolution rules.
For now, this just implments a new condition as semver-minor
so it can be backported to older LTS.
Refs: https://webpack.js.org/guides/package-exports/#target-environment-independent-packages
PR-URL: https://github.com/nodejs/node/pull/54648
Fixes: https://github.com/nodejs/node/issues/52173
Refs: https://github.com/joyeecheung/test-module-condition
Refs: https://github.com/nodejs/node/issues/52697
Reviewed-By: Jacob Smith <jacob@frende.me>
Reviewed-By: Jan Krems <jan.krems@gmail.com>
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
2024-09-25 08:35:26 +02:00
|
|
|
5. If `--experimental-require-module` is enabled
|
|
|
|
a. let CONDITIONS = ["node", "require", "module-sync"]
|
|
|
|
b. Else, let CONDITIONS = ["node", "require"]
|
|
|
|
6. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(DIR/NAME), "." + SUBPATH,
|
|
|
|
`package.json` "exports", CONDITIONS) <a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
|
|
|
|
7. RESOLVE_ESM_MATCH(MATCH)
|
2020-08-09 16:54:01 -07:00
|
|
|
|
|
|
|
LOAD_PACKAGE_SELF(X, DIR)
|
|
|
|
1. Find the closest package scope SCOPE to DIR.
|
|
|
|
2. If no scope was found, return.
|
|
|
|
3. If the SCOPE/package.json "exports" is null or undefined, return.
|
|
|
|
4. If the SCOPE/package.json "name" is not the first segment of X, return.
|
|
|
|
5. let MATCH = PACKAGE_EXPORTS_RESOLVE(pathToFileURL(SCOPE),
|
|
|
|
"." + X.slice("name".length), `package.json` "exports", ["node", "require"])
|
2021-01-29 20:20:53 -05:00
|
|
|
<a href="esm.md#resolver-algorithm-specification">defined in the ESM resolver</a>.
|
2020-08-09 16:54:01 -07:00
|
|
|
6. RESOLVE_ESM_MATCH(MATCH)
|
|
|
|
|
|
|
|
RESOLVE_ESM_MATCH(MATCH)
|
2022-11-20 20:43:10 +09:00
|
|
|
1. let RESOLVED_PATH = fileURLToPath(MATCH)
|
|
|
|
2. If the file at RESOLVED_PATH exists, load RESOLVED_PATH as its extension
|
|
|
|
format. STOP
|
|
|
|
3. THROW "not found"
|
2024-07-06 12:06:46 +01:00
|
|
|
```
|
2019-07-18 21:52:55 -07:00
|
|
|
|
2015-11-04 12:50:07 -05:00
|
|
|
## Caching
|
|
|
|
|
|
|
|
<!--type=misc-->
|
|
|
|
|
2019-03-29 00:07:09 +01:00
|
|
|
Modules are cached after the first time they are loaded. This means (among other
|
|
|
|
things) that every call to `require('foo')` will get exactly the same object
|
|
|
|
returned, if it would resolve to the same file.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2019-03-29 00:07:09 +01:00
|
|
|
Provided `require.cache` is not modified, multiple calls to `require('foo')`
|
|
|
|
will not cause the module code to be executed multiple times. This is an
|
|
|
|
important feature. With it, "partially done" objects can be returned, thus
|
|
|
|
allowing transitive dependencies to be loaded even when they would cause cycles.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2019-03-29 00:07:09 +01:00
|
|
|
To have a module execute code multiple times, export a function, and call that
|
|
|
|
function.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2020-06-14 14:49:34 -07:00
|
|
|
### Module caching caveats
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
<!--type=misc-->
|
|
|
|
|
2019-03-29 00:07:09 +01:00
|
|
|
Modules are cached based on their resolved filename. Since modules may resolve
|
|
|
|
to a different filename based on the location of the calling module (loading
|
2021-10-10 21:55:04 -07:00
|
|
|
from `node_modules` folders), it is not a _guarantee_ that `require('foo')` will
|
2019-03-29 00:07:09 +01:00
|
|
|
always return the exact same object, if it would resolve to different files.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2016-02-19 21:55:23 +01:00
|
|
|
Additionally, on case-insensitive file systems or operating systems, different
|
|
|
|
resolved filenames can point to the same file, but the cache will still treat
|
|
|
|
them as different modules and will reload the file multiple times. For example,
|
|
|
|
`require('./foo')` and `require('./FOO')` return two different objects,
|
|
|
|
irrespective of whether or not `./foo` and `./FOO` are the same file.
|
|
|
|
|
2024-05-07 09:50:31 +08:00
|
|
|
## Built-in modules
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
<!--type=misc-->
|
2021-09-19 17:18:42 -07:00
|
|
|
|
2021-02-06 12:10:00 +01:00
|
|
|
<!-- YAML
|
|
|
|
changes:
|
2021-09-04 15:29:35 +02:00
|
|
|
- version:
|
|
|
|
- v16.0.0
|
|
|
|
- v14.18.0
|
2021-02-06 12:10:00 +01:00
|
|
|
pr-url: https://github.com/nodejs/node/pull/37246
|
|
|
|
description: Added `node:` import support to `require(...)`.
|
|
|
|
-->
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2018-04-02 08:38:48 +03:00
|
|
|
Node.js has several modules compiled into the binary. These modules are
|
2015-11-04 12:50:07 -05:00
|
|
|
described in greater detail elsewhere in this documentation.
|
|
|
|
|
2024-05-07 09:50:31 +08:00
|
|
|
The built-in modules are defined within the Node.js source and are located in the
|
2015-11-04 12:50:07 -05:00
|
|
|
`lib/` folder.
|
|
|
|
|
2024-08-22 17:52:53 -07:00
|
|
|
Built-in modules can be identified using the `node:` prefix, in which case
|
2021-02-06 12:10:00 +01:00
|
|
|
it bypasses the `require` cache. For instance, `require('node:http')` will
|
|
|
|
always return the built in HTTP module, even if there is `require.cache` entry
|
|
|
|
by that name.
|
|
|
|
|
2024-05-07 09:50:31 +08:00
|
|
|
Some built-in modules are always preferentially loaded if their identifier is
|
2022-04-20 01:34:02 +02:00
|
|
|
passed to `require()`. For instance, `require('http')` will always
|
2025-02-16 22:31:15 +00:00
|
|
|
return the built-in HTTP module, even if there is a file by that name.
|
|
|
|
|
|
|
|
The list of all the built-in modules can be retrieved from [`module.builtinModules`][].
|
|
|
|
The modules being all listed without the `node:` prefix, except those that mandate such
|
|
|
|
prefix (as explained in the next section).
|
2022-04-20 01:34:02 +02:00
|
|
|
|
2024-05-07 09:50:31 +08:00
|
|
|
### Built-in modules with mandatory `node:` prefix
|
|
|
|
|
|
|
|
When being loaded by `require()`, some built-in modules must be requested with the
|
|
|
|
`node:` prefix. This requirement exists to prevent newly introduced built-in
|
|
|
|
modules from having a conflict with user land packages that already have
|
|
|
|
taken the name. Currently the built-in modules that requires the `node:` prefix are:
|
|
|
|
|
|
|
|
* [`node:sea`][]
|
2024-11-16 13:05:45 +09:00
|
|
|
* [`node:sqlite`][]
|
2024-05-07 09:50:31 +08:00
|
|
|
* [`node:test`][]
|
|
|
|
* [`node:test/reporters`][]
|
|
|
|
|
2024-12-13 23:35:00 -08:00
|
|
|
The list of these modules is exposed in [`module.builtinModules`][], including the prefix.
|
|
|
|
|
2012-02-27 11:09:34 -08:00
|
|
|
## Cycles
|
|
|
|
|
|
|
|
<!--type=misc-->
|
2011-09-13 10:59:42 -07:00
|
|
|
|
2014-10-04 10:50:50 -04:00
|
|
|
When there are circular `require()` calls, a module might not have finished
|
|
|
|
executing when it is returned.
|
2011-09-13 10:59:42 -07:00
|
|
|
|
|
|
|
Consider this situation:
|
|
|
|
|
|
|
|
`a.js`:
|
|
|
|
|
2016-07-09 08:13:09 +03:00
|
|
|
```js
|
2016-01-17 18:39:07 +01:00
|
|
|
console.log('a starting');
|
|
|
|
exports.done = false;
|
|
|
|
const b = require('./b.js');
|
|
|
|
console.log('in a, b.done = %j', b.done);
|
|
|
|
exports.done = true;
|
|
|
|
console.log('a done');
|
|
|
|
```
|
2011-09-13 10:59:42 -07:00
|
|
|
|
|
|
|
`b.js`:
|
|
|
|
|
2016-07-09 08:13:09 +03:00
|
|
|
```js
|
2016-01-17 18:39:07 +01:00
|
|
|
console.log('b starting');
|
|
|
|
exports.done = false;
|
|
|
|
const a = require('./a.js');
|
|
|
|
console.log('in b, a.done = %j', a.done);
|
|
|
|
exports.done = true;
|
|
|
|
console.log('b done');
|
|
|
|
```
|
2011-09-13 10:59:42 -07:00
|
|
|
|
|
|
|
`main.js`:
|
|
|
|
|
2016-07-09 08:13:09 +03:00
|
|
|
```js
|
2016-01-17 18:39:07 +01:00
|
|
|
console.log('main starting');
|
|
|
|
const a = require('./a.js');
|
|
|
|
const b = require('./b.js');
|
2018-04-02 08:38:48 +03:00
|
|
|
console.log('in main, a.done = %j, b.done = %j', a.done, b.done);
|
2016-01-17 18:39:07 +01:00
|
|
|
```
|
2011-09-13 10:59:42 -07:00
|
|
|
|
2018-04-02 08:38:48 +03:00
|
|
|
When `main.js` loads `a.js`, then `a.js` in turn loads `b.js`. At that
|
|
|
|
point, `b.js` tries to load `a.js`. In order to prevent an infinite
|
2014-10-04 10:50:50 -04:00
|
|
|
loop, an **unfinished copy** of the `a.js` exports object is returned to the
|
2018-04-02 08:38:48 +03:00
|
|
|
`b.js` module. `b.js` then finishes loading, and its `exports` object is
|
2011-09-13 10:59:42 -07:00
|
|
|
provided to the `a.js` module.
|
|
|
|
|
|
|
|
By the time `main.js` has loaded both modules, they're both finished.
|
|
|
|
The output of this program would thus be:
|
|
|
|
|
2019-09-01 11:07:24 +08:00
|
|
|
```console
|
2016-01-17 18:39:07 +01:00
|
|
|
$ node main.js
|
|
|
|
main starting
|
|
|
|
a starting
|
|
|
|
b starting
|
|
|
|
in b, a.done = false
|
|
|
|
b done
|
|
|
|
in a, b.done = true
|
|
|
|
a done
|
2018-04-02 08:38:48 +03:00
|
|
|
in main, a.done = true, b.done = true
|
2016-01-17 18:39:07 +01:00
|
|
|
```
|
2011-09-13 10:59:42 -07:00
|
|
|
|
2017-04-26 10:16:12 -07:00
|
|
|
Careful planning is required to allow cyclic module dependencies to work
|
|
|
|
correctly within an application.
|
2011-09-13 10:59:42 -07:00
|
|
|
|
2020-06-14 14:49:34 -07:00
|
|
|
## File modules
|
2012-02-27 11:09:34 -08:00
|
|
|
|
|
|
|
<!--type=misc-->
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2015-08-13 12:14:34 -04:00
|
|
|
If the exact filename is not found, then Node.js will attempt to load the
|
2015-08-14 10:09:30 -07:00
|
|
|
required filename with the added extensions: `.js`, `.json`, and finally
|
2022-01-02 18:20:02 +01:00
|
|
|
`.node`. When loading a file that has a different extension (e.g. `.cjs`), its
|
|
|
|
full name must be passed to `require()`, including its file extension (e.g.
|
|
|
|
`require('./file.cjs')`).
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2022-01-02 18:20:02 +01:00
|
|
|
`.json` files are parsed as JSON text files, `.node` files are interpreted as
|
|
|
|
compiled addon modules loaded with `process.dlopen()`. Files using any other
|
|
|
|
extension (or no extension at all) are parsed as JavaScript text files. Refer to
|
|
|
|
the [Determining module system][] section to understand what parse goal will be
|
|
|
|
used.
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2018-04-02 08:38:48 +03:00
|
|
|
A required module prefixed with `'/'` is an absolute path to the file. For
|
2011-02-09 13:56:59 -08:00
|
|
|
example, `require('/home/marco/foo.js')` will load the file at
|
|
|
|
`/home/marco/foo.js`.
|
2010-10-28 23:18:16 +11:00
|
|
|
|
2015-08-14 10:09:30 -07:00
|
|
|
A required module prefixed with `'./'` is relative to the file calling
|
|
|
|
`require()`. That is, `circle.js` must be in the same directory as `foo.js` for
|
2010-10-28 23:18:16 +11:00
|
|
|
`require('./circle')` to find it.
|
|
|
|
|
2018-04-29 20:46:41 +03:00
|
|
|
Without a leading `'/'`, `'./'`, or `'../'` to indicate a file, the module must
|
2015-08-14 10:09:30 -07:00
|
|
|
either be a core module or is loaded from a `node_modules` folder.
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2022-01-24 22:59:26 +01:00
|
|
|
If the given path does not exist, `require()` will throw a
|
|
|
|
[`MODULE_NOT_FOUND`][] error.
|
2011-12-18 13:31:16 -08:00
|
|
|
|
2020-06-14 14:49:34 -07:00
|
|
|
## Folders as modules
|
2012-02-27 11:09:34 -08:00
|
|
|
|
|
|
|
<!--type=misc-->
|
2011-02-09 13:28:30 -08:00
|
|
|
|
2022-01-18 19:13:44 +01:00
|
|
|
> Stability: 3 - Legacy: Use [subpath exports][] or [subpath imports][] instead.
|
|
|
|
|
2011-02-09 13:56:59 -08:00
|
|
|
There are three ways in which a folder may be passed to `require()` as
|
|
|
|
an argument.
|
2011-02-09 13:28:30 -08:00
|
|
|
|
2020-08-07 13:12:25 +02:00
|
|
|
The first is to create a [`package.json`][] file in the root of the folder,
|
|
|
|
which specifies a `main` module. An example [`package.json`][] file might
|
2011-02-09 13:56:59 -08:00
|
|
|
look like this:
|
2010-10-28 23:18:16 +11:00
|
|
|
|
2016-07-09 08:13:09 +03:00
|
|
|
```json
|
2016-01-17 18:39:07 +01:00
|
|
|
{ "name" : "some-library",
|
|
|
|
"main" : "./lib/some-library.js" }
|
|
|
|
```
|
2011-02-09 13:56:59 -08:00
|
|
|
|
|
|
|
If this was in a folder at `./some-library`, then
|
|
|
|
`require('./some-library')` would attempt to load
|
|
|
|
`./some-library/lib/some-library.js`.
|
|
|
|
|
2020-08-07 13:12:25 +02:00
|
|
|
If there is no [`package.json`][] file present in the directory, or if the
|
|
|
|
[`"main"`][] entry is missing or cannot be resolved, then Node.js
|
2011-02-09 13:56:59 -08:00
|
|
|
will attempt to load an `index.js` or `index.node` file out of that
|
2020-08-07 13:12:25 +02:00
|
|
|
directory. For example, if there was no [`package.json`][] file in the previous
|
2011-02-09 13:56:59 -08:00
|
|
|
example, then `require('./some-library')` would attempt to load:
|
|
|
|
|
|
|
|
* `./some-library/index.js`
|
|
|
|
* `./some-library/index.node`
|
|
|
|
|
2018-08-22 16:28:18 -07:00
|
|
|
If these attempts fail, then Node.js will report the entire module as missing
|
|
|
|
with the default error:
|
|
|
|
|
2020-04-23 11:01:52 -07:00
|
|
|
```console
|
2018-08-22 16:28:18 -07:00
|
|
|
Error: Cannot find module 'some-library'
|
|
|
|
```
|
|
|
|
|
2022-01-18 19:13:44 +01:00
|
|
|
In all three above cases, an `import('./some-library')` call would result in a
|
|
|
|
[`ERR_UNSUPPORTED_DIR_IMPORT`][] error. Using package [subpath exports][] or
|
|
|
|
[subpath imports][] can provide the same containment organization benefits as
|
|
|
|
folders as modules, and work for both `require` and `import`.
|
|
|
|
|
2020-06-14 14:49:34 -07:00
|
|
|
## Loading from `node_modules` folders
|
2012-02-27 11:09:34 -08:00
|
|
|
|
|
|
|
<!--type=misc-->
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2016-12-18 17:21:29 +01:00
|
|
|
If the module identifier passed to `require()` is not a
|
2024-05-07 09:50:31 +08:00
|
|
|
[built-in](#built-in-modules) module, and does not begin with `'/'`, `'../'`, or
|
2022-01-30 15:26:14 +01:00
|
|
|
`'./'`, then Node.js starts at the directory of the current module, and
|
2018-10-29 22:04:25 -07:00
|
|
|
adds `/node_modules`, and attempts to load the module from that location.
|
|
|
|
Node.js will not append `node_modules` to a path already ending in
|
|
|
|
`node_modules`.
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2015-11-04 12:50:07 -05:00
|
|
|
If it is not found there, then it moves to the parent directory, and so
|
|
|
|
on, until the root of the file system is reached.
|
2011-05-16 04:56:40 -07:00
|
|
|
|
2015-11-04 12:50:07 -05:00
|
|
|
For example, if the file at `'/home/ry/projects/foo.js'` called
|
|
|
|
`require('bar.js')`, then Node.js would look in the following locations, in
|
|
|
|
this order:
|
2011-05-16 04:56:40 -07:00
|
|
|
|
2015-11-04 12:50:07 -05:00
|
|
|
* `/home/ry/projects/node_modules/bar.js`
|
|
|
|
* `/home/ry/node_modules/bar.js`
|
|
|
|
* `/home/node_modules/bar.js`
|
|
|
|
* `/node_modules/bar.js`
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2015-11-04 12:50:07 -05:00
|
|
|
This allows programs to localize their dependencies, so that they do not
|
|
|
|
clash.
|
2011-05-16 04:56:40 -07:00
|
|
|
|
2017-04-26 10:16:12 -07:00
|
|
|
It is possible to require specific files or sub modules distributed with a
|
|
|
|
module by including a path suffix after the module name. For instance
|
2015-11-04 12:50:07 -05:00
|
|
|
`require('example-module/path/to/file')` would resolve `path/to/file`
|
|
|
|
relative to where `example-module` is located. The suffixed path follows the
|
|
|
|
same module resolution semantics.
|
|
|
|
|
|
|
|
## Loading from the global folders
|
|
|
|
|
|
|
|
<!-- type=misc -->
|
|
|
|
|
|
|
|
If the `NODE_PATH` environment variable is set to a colon-delimited list
|
|
|
|
of absolute paths, then Node.js will search those paths for modules if they
|
2017-05-20 16:15:58 -04:00
|
|
|
are not found elsewhere.
|
|
|
|
|
2018-02-05 21:55:16 -08:00
|
|
|
On Windows, `NODE_PATH` is delimited by semicolons (`;`) instead of colons.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
`NODE_PATH` was originally created to support loading modules from
|
2019-03-29 00:07:09 +01:00
|
|
|
varying paths before the current [module resolution][] algorithm was defined.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
`NODE_PATH` is still supported, but is less necessary now that the Node.js
|
|
|
|
ecosystem has settled on a convention for locating dependent modules.
|
|
|
|
Sometimes deployments that rely on `NODE_PATH` show surprising behavior
|
2018-04-02 08:38:48 +03:00
|
|
|
when people are unaware that `NODE_PATH` must be set. Sometimes a
|
2015-11-04 12:50:07 -05:00
|
|
|
module's dependencies change, causing a different version (or even a
|
|
|
|
different module) to be loaded as the `NODE_PATH` is searched.
|
|
|
|
|
2021-10-10 21:55:04 -07:00
|
|
|
Additionally, Node.js will search in the following list of GLOBAL\_FOLDERS:
|
2015-11-04 12:50:07 -05:00
|
|
|
|
|
|
|
* 1: `$HOME/.node_modules`
|
|
|
|
* 2: `$HOME/.node_libraries`
|
|
|
|
* 3: `$PREFIX/lib/node`
|
|
|
|
|
2020-02-09 16:09:36 -10:00
|
|
|
Where `$HOME` is the user's home directory, and `$PREFIX` is the Node.js
|
2015-11-04 12:50:07 -05:00
|
|
|
configured `node_prefix`.
|
|
|
|
|
2017-04-26 10:16:12 -07:00
|
|
|
These are mostly for historic reasons.
|
|
|
|
|
2018-02-05 21:55:16 -08:00
|
|
|
It is strongly encouraged to place dependencies in the local `node_modules`
|
|
|
|
folder. These will be loaded faster, and more reliably.
|
2011-05-16 04:56:40 -07:00
|
|
|
|
2016-04-27 23:41:41 +01:00
|
|
|
## The module wrapper
|
|
|
|
|
|
|
|
<!-- type=misc -->
|
|
|
|
|
|
|
|
Before a module's code is executed, Node.js will wrap it with a function
|
|
|
|
wrapper that looks like the following:
|
|
|
|
|
|
|
|
```js
|
2017-04-21 17:38:31 +03:00
|
|
|
(function(exports, require, module, __filename, __dirname) {
|
2017-04-26 10:16:12 -07:00
|
|
|
// Module code actually lives in here
|
2016-04-27 23:41:41 +01:00
|
|
|
});
|
|
|
|
```
|
|
|
|
|
|
|
|
By doing this, Node.js achieves a few things:
|
|
|
|
|
2022-05-14 22:16:44 +02:00
|
|
|
* It keeps top-level variables (defined with `var`, `const`, or `let`) scoped to
|
2020-11-09 05:44:32 -08:00
|
|
|
the module rather than the global object.
|
2019-09-13 00:22:29 -04:00
|
|
|
* It helps to provide some global-looking variables that are actually specific
|
2019-09-07 22:44:35 -04:00
|
|
|
to the module, such as:
|
2019-09-13 00:22:29 -04:00
|
|
|
* The `module` and `exports` objects that the implementor can use to export
|
|
|
|
values from the module.
|
|
|
|
* The convenience variables `__filename` and `__dirname`, containing the
|
|
|
|
module's absolute filename and directory path.
|
2016-04-27 23:41:41 +01:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
## The module scope
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `__dirname`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.27
|
|
|
|
-->
|
|
|
|
|
|
|
|
<!-- type=var -->
|
|
|
|
|
|
|
|
* {string}
|
|
|
|
|
2018-01-24 14:30:58 +04:00
|
|
|
The directory name of the current module. This is the same as the
|
2017-06-28 18:14:23 +02:00
|
|
|
[`path.dirname()`][] of the [`__filename`][].
|
|
|
|
|
|
|
|
Example: running `node example.js` from `/Users/mjr`
|
|
|
|
|
|
|
|
```js
|
|
|
|
console.log(__dirname);
|
|
|
|
// Prints: /Users/mjr
|
|
|
|
console.log(path.dirname(__filename));
|
|
|
|
// Prints: /Users/mjr
|
|
|
|
```
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `__filename`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.0.1
|
|
|
|
-->
|
|
|
|
|
|
|
|
<!-- type=var -->
|
|
|
|
|
|
|
|
* {string}
|
|
|
|
|
2018-11-23 21:00:40 -08:00
|
|
|
The file name of the current module. This is the current module file's absolute
|
|
|
|
path with symlinks resolved.
|
2017-06-28 18:14:23 +02:00
|
|
|
|
|
|
|
For a main program this is not necessarily the same as the file name used in the
|
|
|
|
command line.
|
|
|
|
|
|
|
|
See [`__dirname`][] for the directory name of the current module.
|
|
|
|
|
|
|
|
Examples:
|
|
|
|
|
|
|
|
Running `node example.js` from `/Users/mjr`
|
|
|
|
|
|
|
|
```js
|
|
|
|
console.log(__filename);
|
|
|
|
// Prints: /Users/mjr/example.js
|
|
|
|
console.log(__dirname);
|
|
|
|
// Prints: /Users/mjr
|
|
|
|
```
|
|
|
|
|
|
|
|
Given two modules: `a` and `b`, where `b` is a dependency of
|
|
|
|
`a` and there is a directory structure of:
|
|
|
|
|
|
|
|
* `/Users/mjr/app/a.js`
|
|
|
|
* `/Users/mjr/app/node_modules/b/b.js`
|
|
|
|
|
|
|
|
References to `__filename` within `b.js` will return
|
|
|
|
`/Users/mjr/app/node_modules/b/b.js` while references to `__filename` within
|
|
|
|
`a.js` will return `/Users/mjr/app/a.js`.
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `exports`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.12
|
|
|
|
-->
|
|
|
|
|
|
|
|
<!-- type=var -->
|
|
|
|
|
2019-01-06 00:44:49 +02:00
|
|
|
* {Object}
|
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
A reference to the `module.exports` that is shorter to type.
|
|
|
|
See the section about the [exports shortcut][] for details on when to use
|
|
|
|
`exports` and when to use `module.exports`.
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
|
|
|
-->
|
|
|
|
|
|
|
|
<!-- type=var -->
|
|
|
|
|
2019-01-06 00:44:49 +02:00
|
|
|
* {module}
|
2017-06-28 18:14:23 +02:00
|
|
|
|
|
|
|
A reference to the current module, see the section about the
|
|
|
|
[`module` object][]. In particular, `module.exports` is used for defining what
|
|
|
|
a module exports and makes available through `require()`.
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `require(id)`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.13
|
|
|
|
-->
|
|
|
|
|
|
|
|
<!-- type=var -->
|
|
|
|
|
2019-01-06 00:44:49 +02:00
|
|
|
* `id` {string} module name or path
|
|
|
|
* Returns: {any} exported module content
|
2017-06-28 18:14:23 +02:00
|
|
|
|
2018-10-12 11:33:59 -07:00
|
|
|
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
|
2020-01-29 21:12:59 +02:00
|
|
|
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.
|
2018-10-12 11:33:59 -07:00
|
|
|
|
|
|
|
```js
|
2020-01-29 21:12:59 +02:00
|
|
|
// Importing a local module with a path relative to the `__dirname` or current
|
|
|
|
// working directory. (On Windows, this would resolve to .\path\myLocalModule.)
|
2018-10-12 11:33:59 -07:00
|
|
|
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:
|
2022-04-20 10:23:41 +02:00
|
|
|
const crypto = require('node:crypto');
|
2018-10-12 11:33:59 -07:00
|
|
|
```
|
2017-06-28 18:14:23 +02:00
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
#### `require.cache`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.3.0
|
|
|
|
-->
|
|
|
|
|
|
|
|
* {Object}
|
|
|
|
|
|
|
|
Modules are cached in this object when they are required. By deleting a key
|
2019-06-20 13:41:00 -06:00
|
|
|
value from this object, the next `require` will reload the module.
|
|
|
|
This does not apply to [native addons][], for which reloading will result in an
|
2018-04-29 20:46:41 +03:00
|
|
|
error.
|
2017-06-28 18:14:23 +02:00
|
|
|
|
2019-03-29 00:07:09 +01:00
|
|
|
Adding or replacing entries is also possible. This cache is checked before
|
2022-08-05 02:32:06 +08:00
|
|
|
built-in modules and if a name matching a built-in module is added to the cache,
|
|
|
|
only `node:`-prefixed require calls are going to receive the built-in module.
|
2021-02-06 12:10:00 +01:00
|
|
|
Use with care!
|
|
|
|
|
2024-11-20 19:10:38 +09:00
|
|
|
<!-- eslint-disable node-core/no-duplicate-requires, no-restricted-syntax -->
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2021-02-06 12:10:00 +01:00
|
|
|
```js
|
2022-04-20 10:23:41 +02:00
|
|
|
const assert = require('node:assert');
|
|
|
|
const realFs = require('node:fs');
|
2021-02-06 12:10:00 +01:00
|
|
|
|
|
|
|
const fakeFs = {};
|
|
|
|
require.cache.fs = { exports: fakeFs };
|
|
|
|
|
2022-10-02 12:15:09 +02:00
|
|
|
assert.strictEqual(require('fs'), fakeFs);
|
2021-02-06 12:10:00 +01:00
|
|
|
assert.strictEqual(require('node:fs'), realFs);
|
|
|
|
```
|
2019-03-29 00:07:09 +01:00
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
#### `require.extensions`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.3.0
|
|
|
|
deprecated: v0.10.6
|
|
|
|
-->
|
|
|
|
|
|
|
|
> Stability: 0 - Deprecated
|
|
|
|
|
|
|
|
* {Object}
|
|
|
|
|
|
|
|
Instruct `require` on how to handle certain file extensions.
|
|
|
|
|
|
|
|
Process files with the extension `.sjs` as `.js`:
|
|
|
|
|
|
|
|
```js
|
|
|
|
require.extensions['.sjs'] = require.extensions['.js'];
|
|
|
|
```
|
|
|
|
|
2019-03-29 00:07:09 +01:00
|
|
|
**Deprecated.** In the past, this list has been used to load non-JavaScript
|
|
|
|
modules into Node.js by compiling them on-demand. However, in practice, there
|
|
|
|
are much better ways to do this, such as loading modules via some other Node.js
|
|
|
|
program, or compiling them to JavaScript ahead of time.
|
2017-06-28 18:14:23 +02:00
|
|
|
|
2019-03-29 00:07:09 +01:00
|
|
|
Avoid using `require.extensions`. Use could cause subtle bugs and resolving the
|
|
|
|
extensions gets slower with each registered extension.
|
2017-06-28 18:14:23 +02:00
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
#### `require.main`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2018-03-24 14:22:19 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.17
|
|
|
|
-->
|
|
|
|
|
2022-01-05 11:05:25 +01:00
|
|
|
* {module | undefined}
|
2018-03-24 14:22:19 +02:00
|
|
|
|
|
|
|
The `Module` object representing the entry script loaded when the Node.js
|
2022-01-05 11:05:25 +01:00
|
|
|
process launched, or `undefined` if the entry point of the program is not a
|
|
|
|
CommonJS module.
|
2021-07-04 20:39:17 -07:00
|
|
|
See ["Accessing the main module"](#accessing-the-main-module).
|
2018-03-24 14:22:19 +02:00
|
|
|
|
|
|
|
In `entry.js` script:
|
|
|
|
|
|
|
|
```js
|
|
|
|
console.log(require.main);
|
|
|
|
```
|
|
|
|
|
2020-05-22 02:33:40 -04:00
|
|
|
```bash
|
2018-03-24 14:22:19 +02:00
|
|
|
node entry.js
|
|
|
|
```
|
|
|
|
|
|
|
|
<!-- eslint-skip -->
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2018-03-24 14:22:19 +02:00
|
|
|
```js
|
|
|
|
Module {
|
|
|
|
id: '.',
|
2020-05-09 13:02:47 +02:00
|
|
|
path: '/absolute/path/to',
|
2018-03-24 14:22:19 +02:00
|
|
|
exports: {},
|
|
|
|
filename: '/absolute/path/to/entry.js',
|
|
|
|
loaded: false,
|
|
|
|
children: [],
|
|
|
|
paths:
|
|
|
|
[ '/absolute/path/to/node_modules',
|
|
|
|
'/absolute/path/node_modules',
|
|
|
|
'/absolute/node_modules',
|
|
|
|
'/node_modules' ] }
|
|
|
|
```
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
#### `require.resolve(request[, options])`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.3.0
|
2016-04-25 12:19:28 -04:00
|
|
|
changes:
|
2017-10-31 00:14:16 +00:00
|
|
|
- version: v8.9.0
|
2016-04-25 12:19:28 -04:00
|
|
|
pr-url: https://github.com/nodejs/node/pull/16397
|
|
|
|
description: The `paths` option is now supported.
|
2017-06-28 18:14:23 +02:00
|
|
|
-->
|
|
|
|
|
2016-04-25 12:19:28 -04:00
|
|
|
* `request` {string} The module path to resolve.
|
|
|
|
* `options` {Object}
|
2021-10-10 21:55:04 -07:00
|
|
|
* `paths` {string\[]} Paths to resolve module location from. If present, these
|
2018-05-05 01:43:12 -04:00
|
|
|
paths are used instead of the default resolution paths, with the exception
|
2021-10-10 21:55:04 -07:00
|
|
|
of [GLOBAL\_FOLDERS][GLOBAL_FOLDERS] like `$HOME/.node_modules`, which are
|
|
|
|
always included. Each of these paths is used as a starting point for
|
2018-05-05 01:43:12 -04:00
|
|
|
the module resolution algorithm, meaning that the `node_modules` hierarchy
|
|
|
|
is checked from this location.
|
2016-04-25 12:19:28 -04:00
|
|
|
* Returns: {string}
|
|
|
|
|
2017-06-28 18:14:23 +02:00
|
|
|
Use the internal `require()` machinery to look up the location of a module,
|
|
|
|
but rather than loading the module, just return the resolved filename.
|
|
|
|
|
2020-03-08 12:13:25 -07:00
|
|
|
If the module can not be found, a `MODULE_NOT_FOUND` error is thrown.
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
##### `require.resolve.paths(request)`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-04-25 12:19:28 -04:00
|
|
|
<!-- YAML
|
2017-10-31 00:14:16 +00:00
|
|
|
added: v8.9.0
|
2016-04-25 12:19:28 -04:00
|
|
|
-->
|
|
|
|
|
|
|
|
* `request` {string} The module path whose lookup paths are being retrieved.
|
2021-10-10 21:55:04 -07:00
|
|
|
* Returns: {string\[]|null}
|
2016-04-25 12:19:28 -04:00
|
|
|
|
2018-01-24 16:54:14 +01:00
|
|
|
Returns an array containing the paths searched during resolution of `request` or
|
2018-04-09 19:30:22 +03:00
|
|
|
`null` if the `request` string references a core module, for example `http` or
|
2018-01-24 16:54:14 +01:00
|
|
|
`fs`.
|
2016-04-25 12:19:28 -04:00
|
|
|
|
2020-06-14 14:49:34 -07:00
|
|
|
## The `module` object
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
|
|
|
-->
|
2012-02-27 11:09:34 -08:00
|
|
|
|
|
|
|
<!-- type=var -->
|
2021-09-19 17:18:42 -07:00
|
|
|
|
2012-02-27 11:09:34 -08:00
|
|
|
<!-- name=module -->
|
|
|
|
|
|
|
|
* {Object}
|
|
|
|
|
|
|
|
In each module, the `module` free variable is a reference to the object
|
2018-04-02 08:38:48 +03:00
|
|
|
representing the current module. For convenience, `module.exports` is
|
2017-01-24 11:37:46 -08:00
|
|
|
also accessible via the `exports` module-global. `module` is not actually
|
2013-10-25 22:03:02 -07:00
|
|
|
a global but rather local to each module.
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module.children`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
|
|
|
-->
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2021-10-10 21:55:04 -07:00
|
|
|
* {module\[]}
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2018-07-05 12:52:53 -04:00
|
|
|
The module objects required for the first time by this one.
|
2015-11-04 12:50:07 -05:00
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module.exports`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
|
|
|
-->
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2012-02-27 11:09:34 -08:00
|
|
|
* {Object}
|
|
|
|
|
2018-04-29 20:46:41 +03:00
|
|
|
The `module.exports` object is created by the `Module` system. Sometimes this is
|
2015-08-13 12:14:34 -04:00
|
|
|
not acceptable; many want their module to be an instance of some class. To do
|
2019-06-20 13:41:00 -06:00
|
|
|
this, assign the desired export object to `module.exports`. Assigning
|
2015-08-13 12:14:34 -04:00
|
|
|
the desired object to `exports` will simply rebind the local `exports` variable,
|
2017-04-26 10:16:12 -07:00
|
|
|
which is probably not what is desired.
|
2013-10-25 22:03:02 -07:00
|
|
|
|
2018-08-26 19:02:27 +03:00
|
|
|
For example, suppose we were making a module called `a.js`:
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
2022-04-20 10:23:41 +02:00
|
|
|
const EventEmitter = require('node:events');
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
module.exports = new EventEmitter();
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
// Do some work, and after some time emit
|
|
|
|
// the 'ready' event from the module itself.
|
|
|
|
setTimeout(() => {
|
|
|
|
module.exports.emit('ready');
|
|
|
|
}, 1000);
|
|
|
|
```
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2018-04-29 14:16:44 +03:00
|
|
|
Then in another file we could do:
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
|
|
|
const a = require('./a');
|
|
|
|
a.on('ready', () => {
|
2018-04-29 20:46:41 +03:00
|
|
|
console.log('module "a" is ready');
|
2016-01-17 18:39:07 +01:00
|
|
|
});
|
|
|
|
```
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2019-06-20 13:41:00 -06:00
|
|
|
Assignment to `module.exports` must be done immediately. It cannot be
|
2018-04-02 08:38:48 +03:00
|
|
|
done in any callbacks. This does not work:
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2018-04-29 20:46:41 +03:00
|
|
|
`x.js`:
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
|
|
|
setTimeout(() => {
|
|
|
|
module.exports = { a: 'hello' };
|
|
|
|
}, 0);
|
|
|
|
```
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2018-04-29 20:46:41 +03:00
|
|
|
`y.js`:
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
|
|
|
const x = require('./x');
|
|
|
|
console.log(x.a);
|
|
|
|
```
|
2011-04-11 16:48:18 -07:00
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
#### `exports` shortcut
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
|
|
|
-->
|
2013-10-25 22:03:02 -07:00
|
|
|
|
2016-11-15 10:31:27 -08:00
|
|
|
The `exports` variable is available within a module's file-level scope, and is
|
|
|
|
assigned the value of `module.exports` before the module is evaluated.
|
|
|
|
|
|
|
|
It allows a shortcut, so that `module.exports.f = ...` can be written more
|
|
|
|
succinctly as `exports.f = ...`. However, be aware that like any variable, if a
|
|
|
|
new value is assigned to `exports`, it is no longer bound to `module.exports`:
|
|
|
|
|
|
|
|
```js
|
|
|
|
module.exports.hello = true; // Exported from require of module
|
|
|
|
exports = { hello: false }; // Not exported, only available in the module
|
|
|
|
```
|
|
|
|
|
|
|
|
When the `module.exports` property is being completely replaced by a new
|
2018-02-20 15:10:10 -08:00
|
|
|
object, it is common to also reassign `exports`:
|
2016-11-15 10:31:27 -08:00
|
|
|
|
2017-04-21 22:55:51 +03:00
|
|
|
<!-- eslint-disable func-name-matching -->
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-11-15 10:31:27 -08:00
|
|
|
```js
|
|
|
|
module.exports = exports = function Constructor() {
|
2017-04-21 07:53:00 +03:00
|
|
|
// ... etc.
|
|
|
|
};
|
2016-11-15 10:31:27 -08:00
|
|
|
```
|
2013-10-25 22:03:02 -07:00
|
|
|
|
2015-09-09 22:21:11 +01:00
|
|
|
To illustrate the behavior, imagine this hypothetical implementation of
|
2016-11-15 10:31:27 -08:00
|
|
|
`require()`, which is quite similar to what is actually done by `require()`:
|
2013-10-25 22:03:02 -07:00
|
|
|
|
2016-01-17 18:39:07 +01:00
|
|
|
```js
|
2017-04-05 04:16:56 +03:00
|
|
|
function require(/* ... */) {
|
|
|
|
const module = { exports: {} };
|
2016-01-24 11:15:51 +02:00
|
|
|
((module, exports) => {
|
2017-04-26 10:16:12 -07:00
|
|
|
// Module code here. In this example, define a function.
|
2017-04-05 04:16:56 +03:00
|
|
|
function someFunc() {}
|
|
|
|
exports = someFunc;
|
2016-11-15 10:31:27 -08:00
|
|
|
// At this point, exports is no longer a shortcut to module.exports, and
|
|
|
|
// this module will still export an empty default object.
|
2017-04-05 04:16:56 +03:00
|
|
|
module.exports = someFunc;
|
|
|
|
// At this point, the module will now export someFunc, instead of the
|
2016-11-15 10:31:27 -08:00
|
|
|
// default object.
|
2016-01-24 11:15:51 +02:00
|
|
|
})(module, module.exports);
|
2016-11-15 10:31:27 -08:00
|
|
|
return module.exports;
|
2016-01-17 18:39:07 +01:00
|
|
|
}
|
|
|
|
```
|
2013-10-25 22:03:02 -07:00
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module.filename`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
|
|
|
-->
|
2011-07-14 13:55:51 -07:00
|
|
|
|
2017-03-05 18:03:39 +01:00
|
|
|
* {string}
|
2011-07-14 13:55:51 -07:00
|
|
|
|
2019-01-06 00:44:49 +02:00
|
|
|
The fully resolved filename of the module.
|
2011-07-14 13:55:51 -07:00
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module.id`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
|
|
|
-->
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2017-03-05 18:03:39 +01:00
|
|
|
* {string}
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2018-04-02 08:38:48 +03:00
|
|
|
The identifier for the module. Typically this is the fully resolved
|
2012-02-27 11:09:34 -08:00
|
|
|
filename.
|
|
|
|
|
2021-01-15 15:46:11 +01:00
|
|
|
### `module.isPreloading`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2021-01-15 15:46:11 +01:00
|
|
|
<!-- YAML
|
2021-05-11, Version 14.17.0 'Fermium' (LTS)
Notable Changes:
Diagnostics channel (experimental module):
`diagnostics_channel` is a new experimental module that provides an API
to create named channels to report arbitrary message data for
diagnostics purposes.
The module was initially introduced in Node.js v15.1.0 and is
backported to v14.17.0 to enable testing it at a larger scale.
With `diagnostics_channel`, Node.js core and module authors can publish
contextual data about what they are doing at a given time. This could
be the hostname and query string of a mysql query, for example. Just
create a named channel with `dc.channel(name)` and call
`channel.publish(data)` to send the data to any listeners to that
channel.
```js
const dc = require('diagnostics_channel');
const channel = dc.channel('mysql.query');
MySQL.prototype.query = function query(queryString, values, callback) {
// Broadcast query information whenever a query is made
channel.publish({
query: queryString,
host: this.hostname,
});
this.doQuery(queryString, values, callback);
};
```
Channels are like one big global event emitter but are split into
separate objects to ensure they get the best performance. If nothing is
listening to the channel, the publishing overhead should be as close to
zero as possible. Consuming channel data is as easy as using
`channel.subscribe(listener)` to run a function whenever a message is
published to that channel.
```js
const dc = require('diagnostics_channel');
const channel = dc.channel('mysql.query');
channel.subscribe(({ query, host }) => {
console.log(`mysql query to ${host}: ${query}`);
});
```
The data captured can be used to provide context for what an app is
doing at a given time. This can be used for things like augmenting
tracing data, tracking network and filesystem activity, logging
queries, and many other things. It's also a very useful data source
for diagnostics tools to provide a clearer picture of exactly what the
application is doing at a given point in the data they are presenting.
Contributed by Stephen Belanger (https://github.com/nodejs/node/pull/34895).
UUID support in the crypto module:
The new `crypto.randomUUID()` method now allows to generate random
[RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) Version 4
UUID strings:
```js
const { randomUUID } = require('crypto');
console.log(randomUUID());
// 'aa7c91a1-f8fc-4339-b9db-f93fc7233429'
```
Contributed by James M Snell (https://github.com/nodejs/node/pull/36729).
Experimental support for `AbortController` and `AbortSignal`:
Node.js 14.17.0 adds experimental partial support for `AbortController`
and `AbortSignal`.
Both constructors can be enabled globally using the
`--experimental-abortcontroller` flag.
Additionally, several Node.js APIs have been updated to support
`AbortSignal` for cancellation.
It is not mandatory to use the built-in constructors with them. Any
spec-compliant third-party alternatives should be compatible.
`AbortSignal` support was added to the following methods:
* `child_process.exec`
* `child_process.execFile`
* `child_process.fork`
* `child_process.spawn`
* `dgram.createSocket`
* `events.on`
* `events.once`
* `fs.readFile`
* `fs.watch`
* `fs.writeFile`
* `http.request`
* `https.request`
* `http2Session.request`
* The promisified variants of `setImmediate` and `setTimeout`
Other notable changes:
* doc:
* revoke deprecation of legacy url, change status to legacy (James M Snell) (https://github.com/nodejs/node/pull/37784)
* add legacy status to stability index (James M Snell) (https://github.com/nodejs/node/pull/37784)
* upgrade stability status of report API (Gireesh Punathil) (https://github.com/nodejs/node/pull/35654)
* deps:
* V8: Backport various patches for Apple Silicon support (BoHong Li) (https://github.com/nodejs/node/pull/38051)
* update ICU to 68.1 (Michaël Zasso) (https://github.com/nodejs/node/pull/36187)
* upgrade to libuv 1.41.0 (Colin Ihrig) (https://github.com/nodejs/node/pull/37360)
* http:
* add http.ClientRequest.getRawHeaderNames() (simov) (https://github.com/nodejs/node/pull/37660)
* report request start and end with diagnostics\_channel (Stephen Belanger) (https://github.com/nodejs/node/pull/34895)
* util:
* add getSystemErrorMap() impl (eladkeyshawn) (https://github.com/nodejs/node/pull/38101)
PR-URL: https://github.com/nodejs/node/pull/38507
2021-05-02 23:12:18 -04:00
|
|
|
added:
|
|
|
|
- v15.4.0
|
|
|
|
- v14.17.0
|
2021-01-15 15:46:11 +01:00
|
|
|
-->
|
|
|
|
|
|
|
|
* Type: {boolean} `true` if the module is running during the Node.js preload
|
|
|
|
phase.
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module.loaded`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
|
|
|
-->
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2017-03-05 18:03:39 +01:00
|
|
|
* {boolean}
|
2012-02-27 11:09:34 -08:00
|
|
|
|
|
|
|
Whether or not the module is done loading, or is in the process of
|
|
|
|
loading.
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module.parent`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.1.16
|
2020-09-28 10:54:13 -07:00
|
|
|
deprecated:
|
|
|
|
- v14.6.0
|
2020-10-01 20:23:33 +02:00
|
|
|
- v12.19.0
|
2016-08-24 12:42:09 +02:00
|
|
|
-->
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2020-03-11 23:44:31 +01:00
|
|
|
> Stability: 0 - Deprecated: Please use [`require.main`][] and
|
|
|
|
> [`module.children`][] instead.
|
|
|
|
|
|
|
|
* {module | null | undefined}
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2020-03-11 23:44:31 +01:00
|
|
|
The module that first required this one, or `null` if the current module is the
|
|
|
|
entry point of the current process, or `undefined` if the module was loaded by
|
2020-10-06 17:50:20 +02:00
|
|
|
something that is not a CommonJS module (E.G.: REPL or `import`).
|
2012-02-27 11:09:34 -08:00
|
|
|
|
2020-05-09 13:02:47 +02:00
|
|
|
### `module.path`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2020-05-09 13:02:47 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v11.14.0
|
|
|
|
-->
|
|
|
|
|
|
|
|
* {string}
|
|
|
|
|
|
|
|
The directory name of the module. This is usually the same as the
|
|
|
|
[`path.dirname()`][] of the [`module.id`][].
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module.paths`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2017-07-23 10:53:37 -04:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.4.0
|
|
|
|
-->
|
|
|
|
|
2021-10-10 21:55:04 -07:00
|
|
|
* {string\[]}
|
2017-07-23 10:53:37 -04:00
|
|
|
|
|
|
|
The search paths for the module.
|
|
|
|
|
2019-12-24 04:36:34 -08:00
|
|
|
### `module.require(id)`
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2016-08-24 12:42:09 +02:00
|
|
|
<!-- YAML
|
|
|
|
added: v0.5.1
|
|
|
|
-->
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2017-02-04 16:15:33 +01:00
|
|
|
* `id` {string}
|
2019-01-06 00:44:49 +02:00
|
|
|
* Returns: {any} exported module content
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2019-01-06 00:44:49 +02:00
|
|
|
The `module.require()` method provides a way to load a module as if
|
2015-11-04 12:50:07 -05:00
|
|
|
`require()` was called from the original module.
|
2011-02-09 13:56:59 -08:00
|
|
|
|
2018-02-05 21:55:16 -08:00
|
|
|
In order to do this, it is necessary to get a reference to the `module` object.
|
|
|
|
Since `require()` returns the `module.exports`, and the `module` is typically
|
2021-10-10 21:55:04 -07:00
|
|
|
_only_ available within a specific module's code, it must be explicitly exported
|
2018-02-05 21:55:16 -08:00
|
|
|
in order to be used.
|
2015-11-13 19:21:49 -08:00
|
|
|
|
2020-06-14 14:49:34 -07:00
|
|
|
## The `Module` object
|
2017-11-24 16:29:38 -05:00
|
|
|
|
2020-08-07 12:16:08 +02:00
|
|
|
This section was moved to
|
2021-07-04 20:39:17 -07:00
|
|
|
[Modules: `module` core module](module.md#the-module-object).
|
2019-09-27 12:12:18 -05:00
|
|
|
|
2020-08-07 12:16:08 +02:00
|
|
|
<!-- Anchors to make sure old links find a target -->
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2021-07-04 20:39:17 -07:00
|
|
|
* <a id="modules_module_builtinmodules" href="module.html#modulebuiltinmodules">`module.builtinModules`</a>
|
|
|
|
* <a id="modules_module_createrequire_filename" href="module.html#modulecreaterequirefilename">`module.createRequire(filename)`</a>
|
|
|
|
* <a id="modules_module_syncbuiltinesmexports" href="module.html#modulesyncbuiltinesmexports">`module.syncBuiltinESMExports()`</a>
|
2019-09-27 12:12:18 -05:00
|
|
|
|
2020-06-14 14:49:34 -07:00
|
|
|
## Source map v3 support
|
2020-01-04 19:17:42 -08:00
|
|
|
|
2020-08-07 12:16:08 +02:00
|
|
|
This section was moved to
|
2021-07-04 20:39:17 -07:00
|
|
|
[Modules: `module` core module](module.md#source-map-v3-support).
|
2020-01-04 19:17:42 -08:00
|
|
|
|
2020-08-07 12:16:08 +02:00
|
|
|
<!-- Anchors to make sure old links find a target -->
|
2021-10-10 21:55:04 -07:00
|
|
|
|
2021-07-04 20:39:17 -07:00
|
|
|
* <a id="modules_module_findsourcemap_path_error" href="module.html#modulefindsourcemappath">`module.findSourceMap(path)`</a>
|
|
|
|
* <a id="modules_class_module_sourcemap" href="module.html#class-modulesourcemap">Class: `module.SourceMap`</a>
|
2025-02-18 20:26:40 +01:00
|
|
|
* <a id="modules_new_sourcemap_payload" href="module.html#new-sourcemappayload--linelengths-">`new SourceMap(payload)`</a>
|
2021-07-04 20:39:17 -07:00
|
|
|
* <a id="modules_sourcemap_payload" href="module.html#sourcemappayload">`sourceMap.payload`</a>
|
2025-02-18 20:26:40 +01:00
|
|
|
* <a id="modules_sourcemap_findentry_linenumber_columnnumber" href="module.html#sourcemapfindentrylineoffset-columnoffset">`sourceMap.findEntry(lineNumber, columnNumber)`</a>
|
2020-01-04 19:17:42 -08:00
|
|
|
|
2022-01-02 18:20:02 +01:00
|
|
|
[Determining module system]: packages.md#determining-module-system
|
2020-09-17 18:53:37 +02:00
|
|
|
[ECMAScript Modules]: esm.md
|
2021-07-04 20:39:17 -07:00
|
|
|
[GLOBAL_FOLDERS]: #loading-from-the-global-folders
|
|
|
|
[`"main"`]: packages.md#main
|
2022-01-17 11:36:19 +01:00
|
|
|
[`"type"`]: packages.md#type
|
2024-12-09 15:47:25 +01:00
|
|
|
[`--trace-require-module`]: cli.md#--trace-require-modulemode
|
module: support require()ing synchronous ESM graphs
This patch adds `require()` support for synchronous ESM graphs under
the flag `--experimental-require-module`
This is based on the the following design aspect of ESM:
- The resolution can be synchronous (up to the host)
- The evaluation of a synchronous graph (without top-level await) is
also synchronous, and, by the time the module graph is instantiated
(before evaluation starts), this is is already known.
If `--experimental-require-module` is enabled, and the ECMAScript
module being loaded by `require()` meets the following requirements:
- Explicitly marked as an ES module with a `"type": "module"` field in
the closest package.json or a `.mjs` extension.
- Fully synchronous (contains no top-level `await`).
`require()` will load the requested module as an ES Module, and return
the module name space object. In this case it is similar to dynamic
`import()` but is run synchronously and returns the name space object
directly.
```mjs
// point.mjs
export function distance(a, b) {
return (b.x - a.x) ** 2 + (b.y - a.y) ** 2;
}
class Point {
constructor(x, y) { this.x = x; this.y = y; }
}
export default Point;
```
```cjs
const required = require('./point.mjs');
// [Module: null prototype] {
// default: [class Point],
// distance: [Function: distance]
// }
console.log(required);
(async () => {
const imported = await import('./point.mjs');
console.log(imported === required); // true
})();
```
If the module being `require()`'d contains top-level `await`, or the
module graph it `import`s contains top-level `await`,
[`ERR_REQUIRE_ASYNC_MODULE`][] will be thrown. In this case, users
should load the asynchronous module using `import()`.
If `--experimental-print-required-tla` is enabled, instead of throwing
`ERR_REQUIRE_ASYNC_MODULE` before evaluation, Node.js will evaluate the
module, try to locate the top-level awaits, and print their location to
help users fix them.
PR-URL: https://github.com/nodejs/node/pull/51977
Reviewed-By: Chengzhong Wu <legendecas@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2024-03-12 01:50:24 +08:00
|
|
|
[`ERR_REQUIRE_ASYNC_MODULE`]: errors.md#err_require_async_module
|
2022-01-18 19:13:44 +01:00
|
|
|
[`ERR_UNSUPPORTED_DIR_IMPORT`]: errors.md#err_unsupported_dir_import
|
2022-01-24 22:59:26 +01:00
|
|
|
[`MODULE_NOT_FOUND`]: errors.md#module_not_found
|
2021-07-04 20:39:17 -07:00
|
|
|
[`__dirname`]: #__dirname
|
|
|
|
[`__filename`]: #__filename
|
2022-07-15 16:44:58 +02:00
|
|
|
[`import()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import
|
2022-04-20 01:34:02 +02:00
|
|
|
[`module.builtinModules`]: module.md#modulebuiltinmodules
|
2021-07-04 20:39:17 -07:00
|
|
|
[`module.children`]: #modulechildren
|
|
|
|
[`module.id`]: #moduleid
|
2022-01-17 11:36:19 +01:00
|
|
|
[`module` core module]: module.md
|
2021-07-04 20:39:17 -07:00
|
|
|
[`module` object]: #the-module-object
|
2024-05-07 09:50:31 +08:00
|
|
|
[`node:sea`]: single-executable-applications.md#single-executable-application-api
|
2024-11-16 13:05:45 +09:00
|
|
|
[`node:sqlite`]: sqlite.md
|
2024-05-07 09:50:31 +08:00
|
|
|
[`node:test/reporters`]: test.md#test-reporters
|
|
|
|
[`node:test`]: test.md
|
2021-07-04 20:39:17 -07:00
|
|
|
[`package.json`]: packages.md#nodejs-packagejson-field-definitions
|
|
|
|
[`path.dirname()`]: path.md#pathdirnamepath
|
2024-10-07 17:26:10 +02:00
|
|
|
[`process.features.require_module`]: process.md#processfeaturesrequire_module
|
2021-07-04 20:39:17 -07:00
|
|
|
[`require.main`]: #requiremain
|
|
|
|
[exports shortcut]: #exports-shortcut
|
2025-02-16 12:00:56 +00:00
|
|
|
[module namespace object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import#module_namespace_object
|
2021-07-04 20:39:17 -07:00
|
|
|
[module resolution]: #all-together
|
2020-09-14 17:09:13 +02:00
|
|
|
[native addons]: addons.md
|
2022-01-18 19:13:44 +01:00
|
|
|
[subpath exports]: packages.md#subpath-exports
|
|
|
|
[subpath imports]: packages.md#subpath-imports
|