0
# Synchronous Resolution
1
2
Synchronous module resolution that implements the Node.js require.resolve() algorithm without callbacks, throwing errors instead of passing them to callback functions. Ideal for build-time processing and initialization scenarios.
3
4
## Capabilities
5
6
### Resolve Sync Function
7
8
Main synchronous resolution function that resolves module path strings into absolute file paths.
9
10
```javascript { .api }
11
/**
12
* Synchronously resolve module path string
13
* @param {string} id - Module path string to resolve
14
* @param {object} [options] - Resolution options
15
* @returns {string} Resolved absolute path to the module
16
* @throws {Error} Resolution or validation errors
17
*/
18
function resolveSync(id, options);
19
```
20
21
**Usage Examples:**
22
23
```javascript
24
const resolve = require('resolve');
25
26
// Basic resolution
27
try {
28
const res = resolve.sync('lodash', { basedir: __dirname });
29
console.log(res); // /path/to/node_modules/lodash/index.js
30
} catch (err) {
31
console.error('Resolution failed:', err.message);
32
}
33
34
// Relative path resolution
35
const helperPath = resolve.sync('./utils/helper', {
36
basedir: '/project/src',
37
extensions: ['.js', '.json']
38
});
39
console.log(helperPath); // /project/src/utils/helper.js
40
41
// Alternative import method
42
const resolveSync = require('resolve/sync');
43
const modulePath = resolveSync('express', { basedir: __dirname });
44
```
45
46
## Resolution Options
47
48
### Basic Configuration
49
50
```javascript { .api }
51
interface SyncResolveOptions {
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 synchronous file system operations for testing, virtualization, or alternative storage backends.
68
69
```javascript { .api }
70
interface SyncFileSystemOptions {
71
/** Custom sync file reading function */
72
readFileSync?: (file: string) => Buffer | string;
73
/** Custom sync file existence test function */
74
isFile?: (file: string) => boolean;
75
/** Custom sync directory existence test function */
76
isDirectory?: (dir: string) => boolean;
77
/** Custom sync symlink resolution function */
78
realpathSync?: (path: string) => string;
79
}
80
```
81
82
**Usage Example:**
83
84
```javascript
85
const fs = require('fs');
86
const resolve = require('resolve');
87
88
const res = resolve.sync('custom-module', {
89
basedir: __dirname,
90
readFileSync: (file) => {
91
console.log('Reading:', file);
92
return fs.readFileSync(file);
93
},
94
isFile: (file) => {
95
try {
96
const stat = fs.statSync(file);
97
return stat.isFile();
98
} catch {
99
return false;
100
}
101
}
102
});
103
```
104
105
### Package Processing Options
106
107
Transform package.json contents and handle custom package processing logic synchronously.
108
109
```javascript { .api }
110
interface SyncPackageOptions {
111
/** Custom sync package.json reading function */
112
readPackageSync?: ReadPackageSyncFunction;
113
/** Transform package.json contents before looking at main field */
114
packageFilter?: (pkg: object, dir: string) => object;
115
/** Transform paths within packages */
116
pathFilter?: (pkg: object, path: string, relativePath: string) => string;
117
/** Custom package candidate path iterator */
118
packageIterator?: PackageIteratorFunction;
119
}
120
121
/**
122
* Custom sync package.json reading function
123
*/
124
interface ReadPackageSyncFunction {
125
(readFileSync: Function, pkgfile: string): object | undefined;
126
}
127
128
/**
129
* Custom package candidate path iterator
130
*/
131
interface PackageIteratorFunction {
132
(request: string, start: string, getPackageCandidates: () => string[], opts: SyncResolveOptions): string[];
133
}
134
```
135
136
**Usage Example:**
137
138
```javascript
139
const resolve = require('resolve');
140
141
const res = resolve.sync('my-package', {
142
basedir: __dirname,
143
packageFilter: (pkg, dir) => {
144
// Note: In sync version, second parameter is dir, not pkgfile
145
// This will change to pkgfile in v2
146
if (pkg.name === 'my-package') {
147
pkg.main = 'dist/index.js';
148
}
149
return pkg;
150
},
151
pathFilter: (pkg, path, relativePath) => {
152
if (pkg.name === 'my-package' && path.endsWith('.js')) {
153
return path.replace('.js', '.min.js');
154
}
155
return path;
156
}
157
});
158
```
159
160
### Path Resolution Options
161
162
Control module search paths and path resolution behavior.
163
164
```javascript { .api }
165
interface SyncPathOptions {
166
/** Custom require.paths array or function for path resolution */
167
paths?: string[] | PathsFunction;
168
}
169
170
/**
171
* Function for custom path resolution logic
172
*/
173
interface PathsFunction {
174
(request: string, start: string, getNodeModulesDirs: () => string[], opts: SyncResolveOptions): string[];
175
}
176
```
177
178
**Usage Example:**
179
180
```javascript
181
const resolve = require('resolve');
182
183
const res = resolve.sync('custom-lib', {
184
basedir: __dirname,
185
paths: (request, start, getNodeModulesDirs, opts) => {
186
const standardPaths = getNodeModulesDirs();
187
return ['/custom/modules', ...standardPaths];
188
}
189
});
190
```
191
192
## Error Handling
193
194
### Error Types
195
196
All sync resolution errors are thrown synchronously instead of being passed to callbacks.
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.
210
211
```javascript
212
const resolve = require('resolve');
213
214
try {
215
resolve.sync('nonexistent-module', { basedir: __dirname });
216
} catch (err) {
217
if (err.code === 'MODULE_NOT_FOUND') {
218
console.error('Module not found:', err.message);
219
// "Cannot find module 'nonexistent-module' from '/current/directory'"
220
}
221
}
222
```
223
224
225
**INVALID_PACKAGE_MAIN**: A package.json was encountered with an invalid main property.
226
227
```javascript
228
try {
229
resolve.sync('broken-package', { basedir: __dirname });
230
} catch (err) {
231
if (err.code === 'INVALID_PACKAGE_MAIN') {
232
console.error('Invalid package main:', err.message);
233
// 'package "broken-package" `main` must be a string'
234
}
235
}
236
```
237
238
## Default Options
239
240
The sync resolver uses the following default options when not specified:
241
242
```javascript { .api }
243
const defaultOptions = {
244
paths: [],
245
basedir: __dirname, // Directory of calling file
246
extensions: ['.js'],
247
includeCoreModules: true,
248
readFileSync: fs.readFileSync,
249
isFile: function(file) {
250
try {
251
const stat = fs.statSync(file, { throwIfNoEntry: false });
252
return !!stat && (stat.isFile() || stat.isFIFO());
253
} catch (e) {
254
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
255
throw e;
256
}
257
},
258
isDirectory: function(dir) {
259
try {
260
const stat = fs.statSync(dir, { throwIfNoEntry: false });
261
return !!stat && stat.isDirectory();
262
} catch (e) {
263
if (e && (e.code === 'ENOENT' || e.code === 'ENOTDIR')) return false;
264
throw e;
265
}
266
},
267
realpathSync: function(file) {
268
try {
269
const realpath = typeof fs.realpathSync.native === 'function'
270
? fs.realpathSync.native
271
: fs.realpathSync;
272
return realpath(file);
273
} catch (realPathErr) {
274
if (realPathErr.code !== 'ENOENT') throw realPathErr;
275
}
276
return file;
277
},
278
readPackageSync: function(readFileSync, pkgfile) {
279
const body = readFileSync(pkgfile);
280
try {
281
return JSON.parse(body);
282
} catch (jsonErr) {
283
// Return undefined for invalid JSON
284
}
285
},
286
moduleDirectory: 'node_modules',
287
preserveSymlinks: true
288
};
289
```