0
# Asynchronous Resolution
1
2
Core asynchronous module resolution functionality that implements the Node.js require.resolve() algorithm with extensive customization options for file system operations, path transformations, and package processing.
3
4
## Capabilities
5
6
### Resolve Function
7
8
Main asynchronous resolution function that resolves module path strings into absolute file paths.
9
10
```javascript { .api }
11
/**
12
* Asynchronously resolve module path string
13
* @param {string} id - Module path string to resolve
14
* @param {object} [options] - Resolution options
15
* @param {function} callback - Callback function (err, res, pkg) => void
16
*/
17
function resolve(id, options, callback);
18
function resolve(id, callback);
19
```
20
21
**Usage Examples:**
22
23
```javascript
24
const resolve = require('resolve');
25
26
// Basic resolution
27
resolve('lodash', { basedir: __dirname }, (err, res) => {
28
if (err) throw err;
29
console.log(res); // /path/to/node_modules/lodash/index.js
30
});
31
32
// Resolution with package info
33
resolve('express', { basedir: __dirname }, (err, res, pkg) => {
34
if (err) throw err;
35
console.log(res); // /path/to/node_modules/express/index.js
36
console.log(pkg); // { name: 'express', version: '4.18.2', ... }
37
});
38
39
// Relative path resolution
40
resolve('./utils/helper', { basedir: '/project/src' }, (err, res) => {
41
if (err) throw err;
42
console.log(res); // /project/src/utils/helper.js
43
});
44
```
45
46
## Resolution Options
47
48
### Basic Configuration
49
50
```javascript { .api }
51
interface AsyncResolveOptions {
52
/** Directory to begin resolving from (default: dirname of calling file) */
53
basedir?: string;
54
/** File extensions to search in order (default: ['.js']) */
55
extensions?: string[];
56
/** Include Node.js core modules in search (default: true) */
57
includeCoreModules?: boolean;
58
/** Don't resolve basedir to real path before resolving (default: true) */
59
preserveSymlinks?: boolean;
60
/** Directory names to search for modules (default: 'node_modules') */
61
moduleDirectory?: string | string[];
62
}
63
```
64
65
### File System Options
66
67
Custom file system operations for testing, virtualization, or alternative storage backends.
68
69
```javascript { .api }
70
interface FileSystemOptions {
71
/** Custom async file reading function */
72
readFile?: (file: string, callback: (err: Error | null, data: Buffer | string) => void) => void;
73
/** Custom async file existence test function */
74
isFile?: (file: string, callback: (err: Error | null, exists: boolean) => void) => void;
75
/** Custom async directory existence test function */
76
isDirectory?: (dir: string, callback: (err: Error | null, exists: boolean) => void) => void;
77
/** Custom async symlink resolution function */
78
realpath?: (path: string, callback: (err: Error | null, realPath: string) => void) => void;
79
}
80
```
81
82
**Usage Example:**
83
84
```javascript
85
const fs = require('fs');
86
87
resolve('custom-module', {
88
basedir: __dirname,
89
readFile: (file, cb) => {
90
console.log('Reading:', file);
91
fs.readFile(file, cb);
92
},
93
isFile: (file, cb) => {
94
fs.stat(file, (err, stat) => {
95
if (err) return cb(null, false);
96
cb(null, stat.isFile());
97
});
98
}
99
}, (err, res) => {
100
// Custom file system operations will be used during resolution
101
});
102
```
103
104
### Package Processing Options
105
106
Transform package.json contents and handle custom package processing logic.
107
108
```javascript { .api }
109
interface PackageOptions {
110
/** package.json data applicable to module being loaded */
111
package?: object;
112
/** Custom async package.json reading function */
113
readPackage?: ReadPackageFunction;
114
/** Transform package.json contents before looking at main field */
115
packageFilter?: (pkg: object, pkgfile: string, dir: string) => object;
116
/** Transform paths within packages */
117
pathFilter?: (pkg: object, path: string, relativePath: string) => string;
118
/** Custom package candidate path iterator */
119
packageIterator?: PackageIteratorFunction;
120
}
121
122
/**
123
* Custom package.json reading function
124
*/
125
interface ReadPackageFunction {
126
(readFile: Function, pkgfile: string, callback: (err: Error | null, pkg?: object) => void): void;
127
}
128
129
/**
130
* Custom package candidate path iterator
131
*/
132
interface PackageIteratorFunction {
133
(request: string, start: string, getPackageCandidates: () => string[], opts: AsyncResolveOptions): string[];
134
}
135
```
136
137
**Usage Example:**
138
139
```javascript
140
resolve('my-package', {
141
basedir: __dirname,
142
packageFilter: (pkg, pkgfile, dir) => {
143
// Transform package.json before resolution
144
if (pkg.name === 'my-package') {
145
pkg.main = 'dist/index.js'; // Override main field
146
}
147
return pkg;
148
},
149
pathFilter: (pkg, path, relativePath) => {
150
// Transform resolved paths
151
if (pkg.name === 'my-package' && path.endsWith('.js')) {
152
return path.replace('.js', '.min.js');
153
}
154
return path;
155
}
156
}, (err, res) => {
157
// Resolution will use transformed package data
158
});
159
```
160
161
### Path Resolution Options
162
163
Control module search paths and path resolution behavior.
164
165
```javascript { .api }
166
interface PathOptions {
167
/** Custom require.paths array or function for path resolution */
168
paths?: string[] | PathsFunction;
169
}
170
171
/**
172
* Function for custom path resolution logic
173
*/
174
interface PathsFunction {
175
(request: string, start: string, getNodeModulesDirs: () => string[], opts: AsyncResolveOptions): string[];
176
}
177
```
178
179
**Usage Example:**
180
181
```javascript
182
resolve('custom-lib', {
183
basedir: __dirname,
184
paths: (request, start, getNodeModulesDirs, opts) => {
185
const standardPaths = getNodeModulesDirs();
186
// Add custom search paths
187
return ['/custom/modules', ...standardPaths];
188
}
189
}, (err, res) => {
190
// Will search in custom paths in addition to standard locations
191
});
192
```
193
194
## Error Handling
195
196
### Error Types
197
198
```javascript { .api }
199
interface ResolveError extends Error {
200
/** Error code indicating the type of resolution failure */
201
code: 'MODULE_NOT_FOUND' | 'INVALID_PACKAGE_MAIN';
202
/** Original error message */
203
message: string;
204
}
205
```
206
207
### Error Scenarios
208
209
**MODULE_NOT_FOUND**: The specified module path could not be resolved after exhausting all search paths.
210
211
```javascript
212
resolve('nonexistent-module', { basedir: __dirname }, (err, res) => {
213
if (err && err.code === 'MODULE_NOT_FOUND') {
214
console.error('Module not found:', err.message);
215
// "Cannot find module 'nonexistent-module' from '/current/directory'"
216
}
217
});
218
```
219
220
221
**INVALID_PACKAGE_MAIN**: A package.json was encountered with an invalid main property.
222
223
```javascript
224
// This can occur if a package.json has main: 123 instead of main: "index.js"
225
resolve('broken-package', { basedir: __dirname }, (err, res) => {
226
if (err && err.code === 'INVALID_PACKAGE_MAIN') {
227
console.error('Invalid package main:', err.message);
228
// 'package "broken-package" `main` must be a string'
229
}
230
});
231
```