0
# Command Line Interface
1
2
Complete CLI functionality for file processing, configuration management, and output formatting. The JSHint CLI provides a comprehensive command-line tool for linting JavaScript files with flexible options and reporting.
3
4
## Capabilities
5
6
### CLI Entry Point
7
8
Main command-line interface entry point that processes arguments and executes linting.
9
10
```javascript { .api }
11
/**
12
* Main CLI entry point that parses command line arguments and runs JSHint
13
* @param args - Command line arguments array in process.argv format
14
*/
15
function interpret(args);
16
```
17
18
**Usage Examples:**
19
20
```bash
21
# Basic file linting
22
jshint file.js
23
24
# Multiple files
25
jshint file1.js file2.js folder/
26
27
# With configuration file
28
jshint --config .jshintrc src/
29
30
# Using custom reporter
31
jshint --reporter unix app.js
32
33
# Reading from stdin
34
echo "var x = 1;" | jshint --stdin
35
36
# With custom filename for stdin
37
echo "var x = 1;" | jshint --stdin --filename test.js
38
```
39
40
### Core CLI Functions
41
42
Core functions that power the command-line interface.
43
44
```javascript { .api }
45
/**
46
* Runs linting with processed CLI options
47
* @param options - Processed CLI options object
48
* @param callback - Optional completion callback function
49
* @returns boolean result or null for async operations
50
*/
51
function run(options, callback);
52
53
/**
54
* Gathers files to be linted based on patterns and options
55
* @param options - File gathering options object
56
* @returns Array of file paths to be processed
57
*/
58
function gather(options);
59
60
/**
61
* Retrieves configuration for a specific file path
62
* @param filepath - File path for configuration lookup
63
* @returns Configuration object merged from various sources
64
*/
65
function getConfig(filepath);
66
67
/**
68
* Loads and parses a JSHint configuration file
69
* @param filepath - Path to configuration file (.jshintrc, package.json, etc.)
70
* @returns Parsed configuration object
71
*/
72
function loadConfig(filepath);
73
74
/**
75
* Extracts JavaScript code from HTML script tags
76
* @param code - Source code string (potentially HTML)
77
* @param when - Extraction mode: 'always', 'auto', or 'never'
78
* @returns Extracted JavaScript code string
79
*/
80
function extract(code, when);
81
82
/**
83
* Exits the process with specified code
84
* @param code - Exit code number (0 for success, non-zero for error)
85
*/
86
function exit(code);
87
```
88
89
**Usage Examples:**
90
91
```javascript
92
const cli = require('jshint/src/cli');
93
94
// Programmatic CLI usage
95
const options = {
96
args: ['file1.js', 'file2.js'],
97
config: '.jshintrc',
98
reporter: 'unix'
99
};
100
101
cli.run(options, (success) => {
102
console.log(success ? 'All files passed!' : 'Errors found');
103
});
104
105
// Gather files for processing
106
const files = cli.gather({
107
args: ['src/'],
108
exclude: ['node_modules/', '*.min.js']
109
});
110
console.log('Files to lint:', files);
111
112
// Extract JavaScript from HTML
113
const html = `
114
<html>
115
<script>
116
function hello() {
117
console.log("Hello World");
118
}
119
</script>
120
</html>
121
`;
122
123
const js = cli.extract(html, 'always');
124
console.log('Extracted JS:', js);
125
```
126
127
### Command Line Options
128
129
Complete set of command-line flags and options supported by JSHint CLI.
130
131
```javascript { .api }
132
interface CLIOptions {
133
// Configuration
134
"--config": string; // -c, Custom configuration file path
135
"--reporter": string; // Custom reporter (path|jslint|checkstyle|unix)
136
137
// File handling
138
"--exclude": string; // File exclusion patterns
139
"--exclude-path": string; // Custom .jshintignore file path
140
"--extra-ext": string; // -e, Additional file extensions (comma-separated)
141
142
// Input/output
143
"--filename": string; // Filename to use for stdin input
144
"--prereq": string; // Comma-separated prerequisite files
145
146
// Output control
147
"--verbose": boolean; // Show error codes in output
148
"--show-non-errors": boolean; // Show additional JSHint data
149
150
// HTML processing
151
"--extract": string; // HTML extraction mode (always|auto|never)
152
}
153
```
154
155
**Usage Examples:**
156
157
```bash
158
# Use custom config file
159
jshint --config custom.jshintrc app.js
160
161
# Use unix-style reporter
162
jshint --reporter unix src/
163
164
# Process additional file extensions
165
jshint --extra-ext .jsx,.ts src/
166
167
# Exclude files and directories
168
jshint --exclude node_modules/,*.min.js src/
169
170
# Use custom .jshintignore file
171
jshint --exclude-path .customignore src/
172
173
# Show error codes
174
jshint --verbose app.js
175
176
# Show additional analysis data
177
jshint --show-non-errors app.js
178
179
# Process HTML files and extract JavaScript
180
jshint --extract always *.html
181
182
# Lint stdin with custom filename
183
echo "var x = 1;" | jshint --stdin --filename test.js
184
185
# Include prerequisite files
186
jshint --prereq jquery.js,underscore.js app.js
187
```
188
189
### File Processing
190
191
File and directory processing capabilities for handling various input scenarios.
192
193
```javascript { .api }
194
/**
195
* File gathering options for processing multiple files and directories
196
*/
197
interface GatherOptions {
198
args: string[]; // File/directory arguments
199
exclude: string[]; // Exclusion patterns
200
excludePath?: string; // Path to .jshintignore file
201
extensions?: string[]; // Additional file extensions
202
}
203
204
/**
205
* Configuration loading hierarchy (in order of precedence):
206
* 1. --config specified file
207
* 2. .jshintrc in file's directory (walking up)
208
* 3. package.json "jshintConfig" property
209
* 4. ~/.jshintrc (user home directory)
210
* 5. Default options
211
*/
212
```
213
214
**Usage Examples:**
215
216
```javascript
217
const cli = require('jshint/src/cli');
218
219
// Advanced file gathering
220
const options = {
221
args: ['src/', 'test/'],
222
exclude: ['node_modules/', '*.min.js', 'vendor/'],
223
extensions: ['.jsx', '.ts']
224
};
225
226
const files = cli.gather(options);
227
files.forEach(file => {
228
const config = cli.getConfig(file);
229
console.log(`Config for ${file}:`, config);
230
});
231
```
232
233
### HTML JavaScript Extraction
234
235
Functionality for extracting and linting JavaScript code embedded in HTML files.
236
237
```javascript { .api }
238
/**
239
* HTML extraction modes for processing JavaScript in HTML files
240
*/
241
type ExtractionMode = 'always' | 'auto' | 'never';
242
243
/**
244
* Extracts JavaScript from HTML script tags
245
* @param code - HTML source code string
246
* @param when - Extraction mode
247
* - 'always': Always extract JS from HTML
248
* - 'auto': Extract only if file extension is .html
249
* - 'never': Never extract, treat as plain JavaScript
250
* @returns Extracted JavaScript code with line number preservation
251
*/
252
function extract(code, when);
253
```
254
255
**Usage Examples:**
256
257
```bash
258
# Extract JavaScript from HTML files
259
jshint --extract always page.html
260
261
# Auto-detect based on file extension
262
jshint --extract auto page.html script.js
263
264
# Process HTML but treat as JavaScript (don't extract)
265
jshint --extract never page.html
266
```
267
268
### Configuration File Formats
269
270
JSHint supports multiple configuration file formats and locations.
271
272
**.jshintrc (JSON format):**
273
```json
274
{
275
"esversion": 6,
276
"strict": true,
277
"undef": true,
278
"unused": true,
279
"predef": ["myGlobal", "anotherGlobal"]
280
}
281
```
282
283
**package.json (jshintConfig property):**
284
```json
285
{
286
"name": "my-package",
287
"jshintConfig": {
288
"node": true,
289
"esversion": 8,
290
"strict": "global"
291
}
292
}
293
```
294
295
**.jshintignore file format:**
296
```
297
node_modules/
298
dist/
299
*.min.js
300
test/fixtures/
301
```
302
303
### Exit Codes
304
305
JSHint CLI uses standard exit codes for integration with build systems:
306
307
- **0**: Success - no linting errors found
308
- **1**: Linting errors found
309
- **2**: Fatal error (invalid arguments, missing files, etc.)
310
311
### Reporter Integration
312
313
```javascript
314
const cli = require('jshint/src/cli');
315
316
// Run with custom reporter
317
const options = {
318
args: ['app.js'],
319
reporter: './custom-reporter.js'
320
};
321
322
cli.run(options);
323
```
324
325
**Custom Reporter Example:**
326
```javascript
327
// custom-reporter.js
328
module.exports = {
329
reporter: function(results, data, opts) {
330
results.forEach(result => {
331
if (result.error) {
332
console.log(`${result.file}: ${result.error.reason}`);
333
}
334
});
335
}
336
};
337
```