0
# File Operations
1
2
License file extraction and JSON parsing utilities for advanced license management workflows.
3
4
## Capabilities
5
6
### License File Extraction
7
8
Extracts individual license files from scanned packages to a specified output directory for compliance archiving and legal review.
9
10
```javascript { .api }
11
/**
12
* Extract license files from packages to output directory
13
* @param data - License data from init() callback
14
* @param outDir - Output directory path for extracted files
15
*/
16
function asFiles(data: LicenseData, outDir: string): void;
17
```
18
19
**Usage Example:**
20
21
```javascript
22
const checker = require("license-checker");
23
const path = require("path");
24
25
checker.init({ start: process.cwd() }, function(err, packages) {
26
if (err) throw err;
27
28
// Extract all license files to ./licenses directory
29
checker.asFiles(packages, "./licenses");
30
31
console.log("License files extracted to ./licenses");
32
});
33
```
34
35
**Behavior:**
36
- Creates the output directory if it doesn't exist (including parent directories)
37
- Copies license files with names formatted as: `{package-name}@{version}-LICENSE.txt`
38
- Only processes packages that have a `licenseFile` path and the file exists
39
- Warns to console for packages without accessible license files
40
- Preserves original file content and encoding
41
42
**Example Output Structure:**
43
```
44
licenses/
45
├── chalk@2.4.2-LICENSE.txt
46
├── debug@3.2.7-LICENSE.txt
47
├── nopt@4.0.3-LICENSE.txt
48
├── mkdirp@0.5.5-LICENSE.txt
49
└── semver@5.7.1-LICENSE.txt
50
```
51
52
**File Naming:**
53
- Package names with scopes: `@angular/core@12.0.0` → `@angular/core@12.0.0-LICENSE.txt`
54
- Special characters preserved in filenames
55
- Consistent `-LICENSE.txt` suffix for all extracted files
56
57
**Error Handling:**
58
- Missing source files: Logs warning and continues processing other packages
59
- Permission errors: Logs warning for inaccessible files
60
- Directory creation failures: Throws error if output directory cannot be created
61
- Invalid paths: Handles and reports path resolution issues
62
63
### JSON File Parsing
64
65
Utility function for parsing JSON files with error handling, commonly used for custom format specifications.
66
67
```javascript { .api }
68
/**
69
* Parse JSON file from filesystem path
70
* @param jsonPath - Absolute or relative path to JSON file
71
* @returns Parsed JSON object or Error instance on failure
72
*/
73
function parseJson(jsonPath: string): object | Error;
74
```
75
76
**Usage Examples:**
77
78
```javascript
79
const checker = require("license-checker");
80
81
// Parse custom format file
82
const customFormat = checker.parseJson("./custom-format.json");
83
84
if (customFormat instanceof Error) {
85
console.error("Failed to parse custom format:", customFormat.message);
86
} else {
87
// Use parsed format with init
88
checker.init({
89
start: process.cwd(),
90
customFormat: customFormat
91
}, callback);
92
}
93
94
// Alternative usage with path validation
95
const formatPath = "./custom-format.json";
96
if (typeof formatPath === "string") {
97
const format = checker.parseJson(formatPath);
98
if (!(format instanceof Error)) {
99
console.log("Loaded custom format:", format);
100
}
101
}
102
```
103
104
**Return Values:**
105
- **Success**: Returns parsed JavaScript object
106
- **File not found**: Returns Error with descriptive message
107
- **Invalid JSON**: Returns Error with parsing details
108
- **Permission denied**: Returns Error with access details
109
- **Invalid path**: Returns Error for non-string paths
110
111
**Error Types:**
112
```javascript
113
// File system errors
114
const result = checker.parseJson("./nonexistent.json");
115
// Returns: Error("ENOENT: no such file or directory...")
116
117
// JSON parsing errors
118
const result = checker.parseJson("./invalid.json");
119
// Returns: Error("Unexpected token } in JSON at position 15")
120
121
// Type validation
122
const result = checker.parseJson(123);
123
// Returns: Error("did not specify a path")
124
```
125
126
**Custom Format File Example:**
127
128
```json
129
{
130
"name": "",
131
"version": "",
132
"licenses": "",
133
"repository": "",
134
"publisher": "",
135
"description": "No description available",
136
"licenseText": false,
137
"copyright": false
138
}
139
```
140
141
### CLI Integration
142
143
Both file operations integrate with the CLI tool:
144
145
```bash
146
# Extract license files to directory
147
license-checker --files ./extracted-licenses
148
149
# Use custom format from JSON file
150
license-checker --customPath ./my-format.json --csv
151
152
# Combine file extraction with other outputs
153
license-checker --files ./licenses --json --out report.json
154
```
155
156
**CLI File Extraction:**
157
- The `--files` flag specifies output directory for license file extraction
158
- Works in combination with other output formats
159
- Creates directory structure automatically
160
- Provides progress feedback for large dependency trees
161
162
**CLI Custom Format:**
163
- The `--customPath` flag loads JSON format specification
164
- Validates file existence and JSON syntax before scanning
165
- Applies custom format to CSV, Markdown, and JSON outputs
166
- Reports parsing errors with helpful messages
167
168
### Integration Patterns
169
170
**Compliance Archiving:**
171
172
```javascript
173
const checker = require("license-checker");
174
const fs = require("fs");
175
const path = require("path");
176
177
function createComplianceReport(projectPath, outputDir) {
178
checker.init({
179
start: projectPath,
180
production: true // Only production dependencies for deployment
181
}, function(err, packages) {
182
if (err) throw err;
183
184
// Extract license files
185
checker.asFiles(packages, path.join(outputDir, "licenses"));
186
187
// Create summary report
188
const summary = checker.asSummary(packages);
189
fs.writeFileSync(path.join(outputDir, "license-summary.txt"), summary);
190
191
// Create detailed CSV
192
const csv = checker.asCSV(packages);
193
fs.writeFileSync(path.join(outputDir, "license-details.csv"), csv);
194
195
console.log(`Compliance report created in ${outputDir}`);
196
});
197
}
198
```
199
200
**Custom Analysis:**
201
202
```javascript
203
// Load analysis configuration
204
const analysisConfig = checker.parseJson("./analysis-config.json");
205
206
if (analysisConfig instanceof Error) {
207
console.error("Configuration error:", analysisConfig.message);
208
process.exit(1);
209
}
210
211
checker.init({
212
start: process.cwd(),
213
customFormat: analysisConfig.format,
214
exclude: analysisConfig.excludeLicenses,
215
production: analysisConfig.productionOnly
216
}, function(err, packages) {
217
// Process results with custom configuration
218
const report = checker.asMarkDown(packages, analysisConfig.format);
219
fs.writeFileSync("analysis-report.md", report);
220
});
221
```