0
# Programmatic API
1
2
The npm-check programmatic API provides a Node.js interface for analyzing package dependencies programmatically. It returns a Promise that resolves to a state object containing all analysis results.
3
4
## Capabilities
5
6
### Main Function
7
8
The primary entry point for npm-check's programmatic interface.
9
10
```javascript { .api }
11
/**
12
* Analyze npm dependencies and return current state
13
* @param options - Configuration options for the analysis
14
* @returns Promise resolving to CurrentState object with analysis results
15
*/
16
function npmCheck(options?: NpmCheckOptions): Promise<CurrentState>;
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const npmCheck = require('npm-check');
23
24
// Basic usage - analyze current directory
25
npmCheck()
26
.then(currentState => {
27
const packages = currentState.get('packages');
28
console.log(`Found ${packages.length} packages`);
29
});
30
31
// With specific options
32
npmCheck({
33
cwd: './my-project',
34
skipUnused: true,
35
ignoreDev: false
36
})
37
.then(currentState => {
38
const outdated = currentState.get('packages')
39
.filter(pkg => pkg.bump && !pkg.notInstalled);
40
console.log(`${outdated.length} packages need updates`);
41
});
42
```
43
44
### Configuration Options
45
46
Complete set of options for customizing npm-check analysis behavior.
47
48
```javascript { .api }
49
interface NpmCheckOptions {
50
/** Check global modules instead of local project */
51
global?: boolean;
52
/** Enable interactive update mode (not typically used programmatically) */
53
update?: boolean;
54
/** Update all packages without prompting (not typically used programmatically) */
55
updateAll?: boolean;
56
/** Skip checking for unused packages */
57
skipUnused?: boolean;
58
/** Only check devDependencies, ignore dependencies */
59
devOnly?: boolean;
60
/** Ignore devDependencies, only check dependencies */
61
ignoreDev?: boolean;
62
/** Working directory to analyze (defaults to process.cwd()) */
63
cwd?: string;
64
/** Save exact versions instead of semver ranges when updating */
65
saveExact?: boolean;
66
/** Pre-existing state object to extend (advanced usage) */
67
currentState?: Object;
68
/** Ignore dependencies matching glob patterns */
69
ignore?: string | string[];
70
/** List of depcheck specials to include */
71
specials?: string;
72
/** Enable debug output */
73
debug?: boolean;
74
/** Enable emoji in output */
75
emoji?: boolean;
76
/** Enable spinner animations */
77
spinner?: boolean;
78
/** Package manager to use for updates */
79
installer?: 'npm' | 'pnpm' | 'yarn' | 'ied' | 'auto';
80
}
81
```
82
83
### Current State Object
84
85
The state object returned by npm-check contains all analysis results and provides methods for accessing data.
86
87
```javascript { .api }
88
interface CurrentState {
89
/**
90
* Get a value from the current state
91
* @param key - State key to retrieve
92
* @returns Value associated with the key
93
*/
94
get(key: StateKey): any;
95
96
/**
97
* Set a value in the current state
98
* @param key - State key to set
99
* @param value - Value to set
100
*/
101
set(key: StateKey, value: any): void;
102
103
/**
104
* Get all state values as an object
105
* @returns Complete state object
106
*/
107
all(): Object;
108
109
/**
110
* Inspect current state if debug mode is enabled
111
*/
112
inspectIfDebugMode(): void;
113
}
114
115
type StateKey =
116
| 'packages' // Array of PackageInfo objects
117
| 'debug' // Debug mode status
118
| 'global' // Global mode status
119
| 'cwd' // Current working directory
120
| 'cwdPackageJson' // Parsed package.json object
121
| 'emoji' // Emoji mode status
122
| 'globalPackages' // Global packages data
123
| 'unusedDependencies' // Unused dependencies array
124
| 'missingFromPackageJson' // Missing packages object
125
| 'update' // Update mode status
126
| 'updateAll' // Update all mode status
127
| 'skipUnused' // Skip unused check status
128
| 'devOnly' // Dev only mode status
129
| 'ignoreDev' // Ignore dev dependencies status
130
| 'saveExact' // Save exact versions status
131
| 'specials' // Depcheck specials
132
| 'spinner' // Spinner enabled status
133
| 'installer' // Package installer to use
134
| 'ignore'; // Ignore patterns for dependencies
135
```
136
137
### Package Analysis Results
138
139
Each package analyzed by npm-check is represented as a PackageInfo object with comprehensive metadata.
140
141
```javascript { .api }
142
interface PackageInfo {
143
/** Name of the npm module */
144
moduleName: string;
145
/** URL to the package's homepage */
146
homepage: string;
147
/** Error encountered when communicating with registry (if any) */
148
regError: any;
149
/** Error encountered when reading package.json (if any) */
150
pkgError: any;
151
/** Latest version available in registry */
152
latest: string;
153
/** Currently installed version */
154
installed: string;
155
/** Whether the package is currently installed */
156
isInstalled: boolean;
157
/** Whether the package is not installed */
158
notInstalled: boolean;
159
/** Requested version from package.json */
160
packageWanted: string;
161
/** Version or range specified in parent package.json */
162
packageJson: string;
163
/** Whether this is listed as a devDependency */
164
devDependency: boolean;
165
/** Array of package.json scripts that reference this module */
166
usedInScripts: string[] | undefined;
167
/** Whether installed version doesn't match package.json range */
168
mismatch: boolean;
169
/** Valid semver version of installed package */
170
semverValid: string;
171
/** Whether running 'npm install' would upgrade this package */
172
easyUpgrade: boolean;
173
/** Type of semver bump needed to reach latest version */
174
bump: 'patch' | 'minor' | 'major' | 'prerelease' | 'build' | 'nonSemver' | null;
175
/** Whether this package appears to be unused in the codebase */
176
unused: boolean;
177
}
178
```
179
180
**Usage Examples:**
181
182
```javascript
183
const npmCheck = require('npm-check');
184
185
npmCheck({ cwd: './my-project' })
186
.then(currentState => {
187
const packages = currentState.get('packages');
188
189
// Find outdated packages
190
const outdated = packages.filter(pkg =>
191
pkg.bump && !pkg.notInstalled
192
);
193
194
// Find unused packages
195
const unused = packages.filter(pkg =>
196
pkg.unused && pkg.isInstalled
197
);
198
199
// Find packages with version mismatches
200
const mismatched = packages.filter(pkg =>
201
pkg.mismatch
202
);
203
204
console.log(`Outdated: ${outdated.length}`);
205
console.log(`Unused: ${unused.length}`);
206
console.log(`Mismatched: ${mismatched.length}`);
207
});
208
```
209
210
### Error Handling
211
212
npm-check handles various error conditions gracefully and includes error information in results.
213
214
```javascript
215
const npmCheck = require('npm-check');
216
217
npmCheck({ cwd: './invalid-path' })
218
.then(currentState => {
219
// Analysis completed - check individual packages for errors
220
const packages = currentState.get('packages');
221
packages.forEach(pkg => {
222
if (pkg.regError) {
223
console.log(`Registry error for ${pkg.moduleName}:`, pkg.regError);
224
}
225
if (pkg.pkgError) {
226
console.log(`Package error for ${pkg.moduleName}:`, pkg.pkgError);
227
}
228
});
229
})
230
.catch(error => {
231
// Critical error prevented analysis
232
console.error('npm-check failed:', error.message);
233
});
234
```