Modules: node:module API | Node.js v22.3.0 Documentation (2024)

Modules: node:module API#

Added in: v0.3.7

The Module object#

Provides general utility methods when interacting with instances ofModule, the module variable often seen in CommonJS modules. Accessedvia import 'node:module' or require('node:module').

module.builtinModules#

Added in: v9.3.0, v8.10.0, v6.13.0

A list of the names of all modules provided by Node.js. Can be used to verifyif a module is maintained by a third party or not.

module in this context isn't the same object that's providedby the module wrapper. To access it, require the Module module:

// module.mjs// In an ECMAScript moduleimport { builtinModules as builtin } from 'node:module';// module.cjs// In a CommonJS moduleconst builtin = require('node:module').builtinModules;

module.createRequire(filename)#

Added in: v12.2.0

  • filename <string> | <URL> Filename to be used to construct the requirefunction. Must be a file URL object, file URL string, or absolute pathstring.
  • Returns: <require> Require function
import { createRequire } from 'node:module';const require = createRequire(import.meta.url);// sibling-module.js is a CommonJS module.const siblingModule = require('./sibling-module'); 

module.isBuiltin(moduleName)#

Added in: v18.6.0, v16.17.0

  • moduleName <string> name of the module
  • Returns: <boolean> returns true if the module is builtin else returns false
import { isBuiltin } from 'node:module';isBuiltin('node:fs'); // trueisBuiltin('fs'); // trueisBuiltin('wss'); // false 

module.register(specifier[, parentURL][, options])#

History
VersionChanges
v20.8.0, v18.19.0

Add support for WHATWG URL instances.

v20.6.0, v18.19.0

Added in: v20.6.0, v18.19.0

Stability: 1.2 - Release candidate

  • specifier <string> | <URL> Customization hooks to be registered; this should bethe same string that would be passed to import(), except that if it isrelative, it is resolved relative to parentURL.
  • parentURL <string> | <URL> If you want to resolve specifier relative to a baseURL, such as import.meta.url, you can pass that URL here. Default:'data:'
  • options <Object>
    • parentURL <string> | <URL> If you want to resolve specifier relative to abase URL, such as import.meta.url, you can pass that URL here. Thisproperty is ignored if the parentURL is supplied as the second argument.Default: 'data:'
    • data <any> Any arbitrary, cloneable JavaScript value to pass into theinitialize hook.
    • transferList <Object[]> transferrable objects to be passed into theinitialize hook.

Register a module that exports hooks that customize Node.js moduleresolution and loading behavior. See Customization hooks.

module.syncBuiltinESMExports()#

Added in: v12.12.0

The module.syncBuiltinESMExports() method updates all the live bindings forbuiltin ES Modules to match the properties of the CommonJS exports. Itdoes not add or remove exported names from the ES Modules.

const fs = require('node:fs');const assert = require('node:assert');const { syncBuiltinESMExports } = require('node:module');fs.readFile = newAPI;delete fs.readFileSync;function newAPI() { // ...}fs.newAPI = newAPI;syncBuiltinESMExports();import('node:fs').then((esmFS) => { // It syncs the existing readFile property with the new value assert.strictEqual(esmFS.readFile, newAPI); // readFileSync has been deleted from the required fs assert.strictEqual('readFileSync' in fs, false); // syncBuiltinESMExports() does not remove readFileSync from esmFS assert.strictEqual('readFileSync' in esmFS, true); // syncBuiltinESMExports() does not add names assert.strictEqual(esmFS.newAPI, undefined);}); 

Customization Hooks#

History
VersionChanges
v20.6.0, v18.19.0

Added initialize hook to replace globalPreload.

v18.6.0, v16.17.0

Add support for chaining loaders.

v16.12.0

Removed getFormat, getSource, transformSource, and globalPreload; added load hook and getGlobalPreload hook.

v8.8.0

Added in: v8.8.0

Stability: 1.2 - Release candidate

Enabling#

Module resolution and loading can be customized by registering a file whichexports a set of hooks. This can be done using the register methodfrom node:module, which you can run before your application code byusing the --import flag:

node --import ./register-hooks.js ./my-app.js 
// register-hooks.jsimport { register } from 'node:module';register('./hooks.mjs', import.meta.url);// register-hooks.jsconst { register } = require('node:module');const { pathToFileURL } = require('node:url');register('./hooks.mjs', pathToFileURL(__filename));

The file passed to --import can also be an export from a dependency:

node --import some-package/register ./my-app.js 

Where some-package has an "exports" field defining the /registerexport to map to a file that calls register(), like the following register-hooks.jsexample.

Using --import ensures that the hooks are registered before any applicationfiles are imported, including the entry point of the application. Alternatively,register can be called from the entry point, but dynamic import() must beused for any code that should be run after the hooks are registered:

import { register } from 'node:module';register('http-to-https', import.meta.url);// Because this is a dynamic `import()`, the `http-to-https` hooks will run// to handle `./my-app.js` and any other files it imports or requires.await import('./my-app.js');const { register } = require('node:module');const { pathToFileURL } = require('node:url');register('http-to-https', pathToFileURL(__filename));// Because this is a dynamic `import()`, the `http-to-https` hooks will run// to handle `./my-app.js` and any other files it imports or requires.import('./my-app.js');

In this example, we are registering the http-to-https hooks, but they willonly be available for subsequently imported modules—in this case, my-app.jsand anything it references via import (and optionally require). If theimport('./my-app.js') had instead been a static import './my-app.js', theapp would have already been loaded before the http-to-https hooks wereregistered. This due to the ES modules specification, where static imports areevaluated from the leaves of the tree first, then back to the trunk. There canbe static imports within my-app.js, which will not be evaluated untilmy-app.js is dynamically imported.

my-app.js can also be CommonJS. Customization hooks will run for anymodules that it references via import (and optionally require).

Finally, if all you want to do is register hooks before your app runs and youdon't want to create a separate file for that purpose, you can pass a data:URL to --import:

node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register("http-to-https", pathToFileURL("./"));' ./my-app.js 

Chaining#

It's possible to call register more than once:

// entrypoint.mjsimport { register } from 'node:module';register('./foo.mjs', import.meta.url);register('./bar.mjs', import.meta.url);await import('./my-app.mjs');// entrypoint.cjsconst { register } = require('node:module');const { pathToFileURL } = require('node:url');const parentURL = pathToFileURL(__filename);register('./foo.mjs', parentURL);register('./bar.mjs', parentURL);import('./my-app.mjs');

In this example, the registered hooks will form chains. These chains runlast-in, first out (LIFO). If both foo.mjs and bar.mjs define a resolvehook, they will be called like so (note the right-to-left):node's default ← ./foo.mjs./bar.mjs(starting with ./bar.mjs, then ./foo.mjs, then the Node.js default).The same applies to all the other hooks.

The registered hooks also affect register itself. In this example,bar.mjs will be resolved and loaded via the hooks registered by foo.mjs(because foo's hooks will have already been added to the chain). This allowsfor things like writing hooks in non-JavaScript languages, so long asearlier registered hooks transpile into JavaScript.

The register method cannot be called from within the module that defines thehooks.

Communication with module customization hooks#

Module customization hooks run on a dedicated thread, separate from the mainthread that runs application code. This means mutating global variables won'taffect the other thread(s), and message channels must be used to communicatebetween the threads.

The register method can be used to pass data to an initialize hook. Thedata passed to the hook may include transferrable objects like ports.

import { register } from 'node:module';import { MessageChannel } from 'node:worker_threads';// This example demonstrates how a message channel can be used to// communicate with the hooks, by sending `port2` to the hooks.const { port1, port2 } = new MessageChannel();port1.on('message', (msg) => { console.log(msg);});register('./my-hooks.mjs', { parentURL: import.meta.url, data: { number: 1, port: port2 }, transferList: [port2],});const { register } = require('node:module');const { pathToFileURL } = require('node:url');const { MessageChannel } = require('node:worker_threads');// This example showcases how a message channel can be used to// communicate with the hooks, by sending `port2` to the hooks.const { port1, port2 } = new MessageChannel();port1.on('message', (msg) => { console.log(msg);});register('./my-hooks.mjs', { parentURL: pathToFileURL(__filename), data: { number: 1, port: port2 }, transferList: [port2],});

Hooks#

The register method can be used to register a module that exports a set ofhooks. The hooks are functions that are called by Node.js to customize themodule resolution and loading process. The exported functions must have specificnames and signatures, and they must be exported as named exports.

export async function initialize({ number, port }) { // Receives data from `register`.}export async function resolve(specifier, context, nextResolve) { // Take an `import` or `require` specifier and resolve it to a URL.}export async function load(url, context, nextLoad) { // Take a resolved URL and return the source code to be evaluated.} 

Hooks are part of a chain, even if that chain consists of only onecustom (user-provided) hook and the default hook, which is always present. Hookfunctions nest: each one must always return a plain object, and chaining happensas a result of each function calling next<hookName>(), which is a reference tothe subsequent loader's hook (in LIFO order).

A hook that returns a value lacking a required property triggers an exception. Ahook that returns without calling next<hookName>() and without returningshortCircuit: true also triggers an exception. These errors are to helpprevent unintentional breaks in the chain. Return shortCircuit: true from ahook to signal that the chain is intentionally ending at your hook.

Hooks are run in a separate thread, isolated from the main thread whereapplication code runs. That means it is a different realm. The hooks threadmay be terminated by the main thread at any time, so do not depend onasynchronous operations (like console.log) to complete.

initialize()#

Added in: v20.6.0, v18.19.0

Stability: 1.2 - Release candidate

  • data <any> The data from register(loader, import.meta.url, { data }).

The initialize hook provides a way to define a custom function that runs inthe hooks thread when the hooks module is initialized. Initialization happenswhen the hooks module is registered via register.

This hook can receive data from a register invocation, includingports and other transferrable objects. The return value of initialize can be a<Promise>, in which case it will be awaited before the main application threadexecution resumes.

Module customization code:

// path-to-my-hooks.jsexport async function initialize({ number, port }) { port.postMessage(`increment: ${number + 1}`);} 

Caller code:

import assert from 'node:assert';import { register } from 'node:module';import { MessageChannel } from 'node:worker_threads';// This example showcases how a message channel can be used to communicate// between the main (application) thread and the hooks running on the hooks// thread, by sending `port2` to the `initialize` hook.const { port1, port2 } = new MessageChannel();port1.on('message', (msg) => { assert.strictEqual(msg, 'increment: 2');});register('./path-to-my-hooks.js', { parentURL: import.meta.url, data: { number: 1, port: port2 }, transferList: [port2],});const assert = require('node:assert');const { register } = require('node:module');const { pathToFileURL } = require('node:url');const { MessageChannel } = require('node:worker_threads');// This example showcases how a message channel can be used to communicate// between the main (application) thread and the hooks running on the hooks// thread, by sending `port2` to the `initialize` hook.const { port1, port2 } = new MessageChannel();port1.on('message', (msg) => { assert.strictEqual(msg, 'increment: 2');});register('./path-to-my-hooks.js', { parentURL: pathToFileURL(__filename), data: { number: 1, port: port2 }, transferList: [port2],});
resolve(specifier, context, nextResolve)#
History
VersionChanges
v21.0.0, v20.10.0, v18.19.0

The property context.importAssertions is replaced with context.importAttributes. Using the old name is still supported and will emit an experimental warning.

v18.6.0, v16.17.0

Add support for chaining resolve hooks. Each hook must either call nextResolve() or include a shortCircuit property set to true in its return.

v17.1.0, v16.14.0

Add support for import assertions.

Stability: 1.2 - Release candidate

  • specifier <string>
  • context <Object>
    • conditions <string[]> Export conditions of the relevant package.json
    • importAttributes <Object> An object whose key-value pairs represent theattributes for the module to import
    • parentURL <string> | <undefined> The module importing this one, or undefinedif this is the Node.js entry point
  • nextResolve <Function> The subsequent resolve hook in the chain, or theNode.js default resolve hook after the last user-supplied resolve hook
  • Returns: <Object> | <Promise>
    • format <string> | <null> | <undefined> A hint to the load hook (it might beignored)'builtin' | 'commonjs' | 'json' | 'module' | 'wasm'
    • importAttributes <Object> | <undefined> The import attributes to use whencaching the module (optional; if excluded the input will be used)
    • shortCircuit <undefined> | <boolean> A signal that this hook intends toterminate the chain of resolve hooks. Default: false
    • url <string> The absolute URL to which this input resolves

Warning Despite support for returning promises and async functions, callsto resolve may block the main thread which can impact performance.

The resolve hook chain is responsible for telling Node.js where to find andhow to cache a given import statement or expression, or require call. It canoptionally return a format (such as 'module') as a hint to the load hook. Ifa format is specified, the load hook is ultimately responsible for providingthe final format value (and it is free to ignore the hint provided byresolve); if resolve provides a format, a custom load hook is requiredeven if only to pass the value to the Node.js default load hook.

Import type attributes are part of the cache key for saving loaded modules intothe internal module cache. The resolve hook is responsible for returning animportAttributes object if the module should be cached with differentattributes than were present in the source code.

The conditions property in context is an array of conditions forpackage exports conditions that apply to this resolutionrequest. They can be used for looking up conditional mappings elsewhere or tomodify the list when calling the default resolution logic.

The current package exports conditions are always inthe context.conditions array passed into the hook. To guarantee defaultNode.js module specifier resolution behavior when calling defaultResolve, thecontext.conditions array passed to it must include all elements of thecontext.conditions array originally passed into the resolve hook.

export async function resolve(specifier, context, nextResolve) { const { parentURL = null } = context; if (Math.random() > 0.5) { // Some condition. // For some or all specifiers, do some custom logic for resolving. // Always return an object of the form {url: <string>}. return { shortCircuit: true, url: parentURL ? new URL(specifier, parentURL).href : new URL(specifier).href, }; } if (Math.random() < 0.5) { // Another condition. // When calling `defaultResolve`, the arguments can be modified. In this // case it's adding another value for matching conditional exports. return nextResolve(specifier, { ...context, conditions: [...context.conditions, 'another-condition'], }); } // Defer to the next hook in the chain, which would be the // Node.js default resolve if this is the last user-specified loader. return nextResolve(specifier);} 
load(url, context, nextLoad)#
History
VersionChanges
v20.6.0

Add support for source with format commonjs.

v18.6.0, v16.17.0

Add support for chaining load hooks. Each hook must either call nextLoad() or include a shortCircuit property set to true in its return.

Stability: 1.2 - Release candidate

The load hook provides a way to define a custom method of determining how aURL should be interpreted, retrieved, and parsed. It is also in charge ofvalidating the import attributes.

The final value of format must be one of the following:

formatDescriptionAcceptable types for source returned by load
'builtin'Load a Node.js builtin moduleNot applicable
'commonjs'Load a Node.js CommonJS module{ string, ArrayBuffer, TypedArray, null, undefined }
'json'Load a JSON file{ string, ArrayBuffer, TypedArray }
'module'Load an ES module{ string, ArrayBuffer, TypedArray }
'wasm'Load a WebAssembly module{ ArrayBuffer, TypedArray }

The value of source is ignored for type 'builtin' because currently it isnot possible to replace the value of a Node.js builtin (core) module.

Omitting vs providing a source for 'commonjs' has very different effects:

  • When a source is provided, all require calls from this module will beprocessed by the ESM loader with registered resolve and load hooks; allrequire.resolve calls from this module will be processed by the ESM loaderwith registered resolve hooks; only a subset of the CommonJS API will beavailable (e.g. no require.extensions, no require.cache, norequire.resolve.paths) and monkey-patching on the CommonJS module loaderwill not apply.
  • If source is undefined or null, it will be handled by the CommonJS moduleloader and require/require.resolve calls will not go through theregistered hooks. This behavior for nullish source is temporary — in thefuture, nullish source will not be supported.

When node is run with --experimental-default-type=commonjs, the Node.jsinternal load implementation, which is the value of next for thelast hook in the load chain, returns null for source when format is'commonjs' for backward compatibility. Here is an example hook that wouldopt-in to using the non-default behavior:

import { readFile } from 'node:fs/promises';export async function load(url, context, nextLoad) { const result = await nextLoad(url, context); if (result.format === 'commonjs') { result.source ??= await readFile(new URL(result.responseURL ?? url)); } return result;} 

Warning: The ESM load hook and namespaced exports from CommonJS modulesare incompatible. Attempting to use them together will result in an emptyobject from the import. This may be addressed in the future.

These types all correspond to classes defined in ECMAScript.

If the source value of a text-based format (i.e., 'json', 'module')is not a string, it is converted to a string using util.TextDecoder.

The load hook provides a way to define a custom method for retrieving thesource code of a resolved URL. This would allow a loader to potentially avoidreading files from disk. It could also be used to map an unrecognized format toa supported one, for example yaml to module.

export async function load(url, context, nextLoad) { const { format } = context; if (Math.random() > 0.5) { // Some condition /* For some or all URLs, do some custom logic for retrieving the source. Always return an object of the form { format: <string>, source: <string|buffer>, }. */ return { format, shortCircuit: true, source: '...', }; } // Defer to the next hook in the chain. return nextLoad(url);} 

In a more advanced scenario, this can also be used to transform an unsupportedsource to a supported one (see Examples below).

Examples#

The various module customization hooks can be used together to accomplishwide-ranging customizations of the Node.js code loading and evaluationbehaviors.

Import from HTTPS#

In current Node.js, specifiers starting with https:// are experimental (seeHTTPS and HTTP imports).

The hook below registers hooks to enable rudimentary support for suchspecifiers. While this may seem like a significant improvement to Node.js corefunctionality, there are substantial downsides to actually using these hooks:performance is much slower than loading files from disk, there is no caching,and there is no security.

// https-hooks.mjsimport { get } from 'node:https';export function load(url, context, nextLoad) { // For JavaScript to be loaded over the network, we need to fetch and // return it. if (url.startsWith('https://')) { return new Promise((resolve, reject) => { get(url, (res) => { let data = ''; res.setEncoding('utf8'); res.on('data', (chunk) => data += chunk); res.on('end', () => resolve({ // This example assumes all network-provided JavaScript is ES module // code. format: 'module', shortCircuit: true, source: data, })); }).on('error', (err) => reject(err)); }); } // Let Node.js handle all other URLs. return nextLoad(url);} 
// main.mjsimport { VERSION } from 'https://coffeescript.org/browser-compiler-modern/coffeescript.js';console.log(VERSION); 

With the preceding hooks module, runningnode --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./https-hooks.mjs"));' ./main.mjsprints the current version of CoffeeScript per the module at the URL inmain.mjs.

Transpilation#

Sources that are in formats Node.js doesn't understand can be converted intoJavaScript using the load hook.

This is less performant than transpiling source files before running Node.js;transpiler hooks should only be used for development and testing purposes.

// coffeescript-hooks.mjsimport { readFile } from 'node:fs/promises';import { dirname, extname, resolve as resolvePath } from 'node:path';import { cwd } from 'node:process';import { fileURLToPath, pathToFileURL } from 'node:url';import coffeescript from 'coffeescript';const extensionsRegex = /\.(coffee|litcoffee|coffee\.md)$/;export async function load(url, context, nextLoad) { if (extensionsRegex.test(url)) { // CoffeeScript files can be either CommonJS or ES modules, so we want any // CoffeeScript file to be treated by Node.js the same as a .js file at the // same location. To determine how Node.js would interpret an arbitrary .js // file, search up the file system for the nearest parent package.json file // and read its "type" field. const format = await getPackageType(url); const { source: rawSource } = await nextLoad(url, { ...context, format }); // This hook converts CoffeeScript source code into JavaScript source code // for all imported CoffeeScript files. const transformedSource = coffeescript.compile(rawSource.toString(), url); return { format, shortCircuit: true, source: transformedSource, }; } // Let Node.js handle all other URLs. return nextLoad(url);}async function getPackageType(url) { // `url` is only a file path during the first iteration when passed the // resolved url from the load() hook // an actual file path from load() will contain a file extension as it's // required by the spec // this simple truthy check for whether `url` contains a file extension will // work for most projects but does not cover some edge-cases (such as // extensionless files or a url ending in a trailing space) const isFilePath = !!extname(url); // If it is a file path, get the directory it's in const dir = isFilePath ? dirname(fileURLToPath(url)) : url; // Compose a file path to a package.json in the same directory, // which may or may not exist const packagePath = resolvePath(dir, 'package.json'); // Try to read the possibly nonexistent package.json const type = await readFile(packagePath, { encoding: 'utf8' }) .then((filestring) => JSON.parse(filestring).type) .catch((err) => { if (err?.code !== 'ENOENT') console.error(err); }); // If package.json existed and contained a `type` field with a value, voilà if (type) return type; // Otherwise, (if not at the root) continue checking the next directory up // If at the root, stop and return false return dir.length > 1 && getPackageType(resolvePath(dir, '..'));} 
# main.coffeeimport { scream } from './scream.coffee'console.log scream 'hello, world'import { version } from 'node:process'console.log "Brought to you by Node.js version #{version}" 
# scream.coffeeexport scream = (str) -> str.toUpperCase() 

With the preceding hooks module, runningnode --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./coffeescript-hooks.mjs"));' ./main.coffeecauses main.coffee to be turned into JavaScript after its source code isloaded from disk but before Node.js executes it; and so on for any .coffee,.litcoffee or .coffee.md files referenced via import statements of anyloaded file.

Import maps#

The previous two examples defined load hooks. This is an example of aresolve hook. This hooks module reads an import-map.json file that defineswhich specifiers to override to other URLs (this is a very simplisticimplementation of a small subset of the "import maps" specification).

// import-map-hooks.jsimport fs from 'node:fs/promises';const { imports } = JSON.parse(await fs.readFile('import-map.json'));export async function resolve(specifier, context, nextResolve) { if (Object.hasOwn(imports, specifier)) { return nextResolve(imports[specifier], context); } return nextResolve(specifier, context);} 

With these files:

// main.jsimport 'a-module'; 
// import-map.json{ "imports": { "a-module": "./some-module.js" }} 
// some-module.jsconsole.log('some module!'); 

Running node --import 'data:text/javascript,import { register } from "node:module"; import { pathToFileURL } from "node:url"; register(pathToFileURL("./import-map-hooks.js"));' main.jsshould print some module!.

Source map v3 support#

Added in: v13.7.0, v12.17.0

Stability: 1 - Experimental

Helpers for interacting with the source map cache. This cache ispopulated when source map parsing is enabled andsource map include directives are found in a modules' footer.

To enable source map parsing, Node.js must be run with the flag--enable-source-maps, or with code coverage enabled by settingNODE_V8_COVERAGE=dir.

// module.mjs// In an ECMAScript moduleimport { findSourceMap, SourceMap } from 'node:module';// module.cjs// In a CommonJS moduleconst { findSourceMap, SourceMap } = require('node:module');

module.findSourceMap(path)#

Added in: v13.7.0, v12.17.0

  • path <string>
  • Returns: <module.SourceMap> | <undefined> Returns module.SourceMap if a sourcemap is found, undefined otherwise.

path is the resolved path for the file for which a corresponding source mapshould be fetched.

Class: module.SourceMap#

Added in: v13.7.0, v12.17.0

new SourceMap(payload[, { lineLengths }])#

Creates a new sourceMap instance.

payload is an object with keys matching the Source map v3 format:

lineLengths is an optional array of the length of each line in thegenerated code.

sourceMap.payload#

Getter for the payload used to construct the SourceMap instance.

sourceMap.findEntry(lineOffset, columnOffset)#
  • lineOffset <number> The zero-indexed line number offset inthe generated source
  • columnOffset <number> The zero-indexed column number offsetin the generated source
  • Returns: <Object>

Given a line offset and column offset in the generated sourcefile, returns an object representing the SourceMap range in theoriginal file if found, or an empty object if not.

The object returned contains the following keys:

  • generatedLine: <number> The line offset of the start of therange in the generated source
  • generatedColumn: <number> The column offset of start of therange in the generated source
  • originalSource: <string> The file name of the original source,as reported in the SourceMap
  • originalLine: <number> The line offset of the start of therange in the original source
  • originalColumn: <number> The column offset of start of therange in the original source
  • name: <string>

The returned value represents the raw range as it appears in theSourceMap, based on zero-indexed offsets, not 1-indexed line andcolumn numbers as they appear in Error messages and CallSiteobjects.

To get the corresponding 1-indexed line and column numbers from alineNumber and columnNumber as they are reported by Error stacksand CallSite objects, use sourceMap.findOrigin(lineNumber, columnNumber)

sourceMap.findOrigin(lineNumber, columnNumber)#
  • lineNumber <number> The 1-indexed line number of the callsite in the generated source
  • columnNumber <number> The 1-indexed column numberof the call site in the generated source
  • Returns: <Object>

Given a 1-indexed lineNumber and columnNumber from a call site inthe generated source, find the corresponding call site locationin the original source.

If the lineNumber and columnNumber provided are not found in anysource map, then an empty object is returned. Otherwise, thereturned object contains the following keys:

  • name: <string> | <undefined> The name of the range in thesource map, if one was provided
  • fileName: <string> The file name of the original source, asreported in the SourceMap
  • lineNumber: <number> The 1-indexed lineNumber of thecorresponding call site in the original source
  • columnNumber: <number> The 1-indexed columnNumber of thecorresponding call site in the original source
Modules: node:module API | Node.js v22.3.0 Documentation (2024)
Top Articles
Latest Posts
Article information

Author: Kareem Mueller DO

Last Updated:

Views: 5978

Rating: 4.6 / 5 (46 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Kareem Mueller DO

Birthday: 1997-01-04

Address: Apt. 156 12935 Runolfsdottir Mission, Greenfort, MN 74384-6749

Phone: +16704982844747

Job: Corporate Administration Planner

Hobby: Mountain biking, Jewelry making, Stone skipping, Lacemaking, Knife making, Scrapbooking, Letterboxing

Introduction: My name is Kareem Mueller DO, I am a vivacious, super, thoughtful, excited, handsome, beautiful, combative person who loves writing and wants to share my knowledge and understanding with you.