0
# File Utilities
1
2
Internal utilities for file operations, template processing, and JSON manipulation used by the @js-lib/cli tool. These utilities provide comprehensive file system operations for scaffolding and updating projects.
3
4
## Capabilities
5
6
### File Existence Checking
7
8
Check if files or directories exist at the specified path.
9
10
```javascript { .api }
11
/**
12
* Check if a file or directory exists at the specified path
13
* @param cmdPath - Base directory path
14
* @param name - File or directory name to check
15
* @returns true if file/directory exists, false otherwise
16
*/
17
function checkProjectExists(cmdPath: string, name: string): boolean;
18
```
19
20
**Usage Examples:**
21
22
```javascript
23
const { checkProjectExists } = require('@js-lib/cli/util/file');
24
25
// Check if project directory exists
26
const exists = checkProjectExists(process.cwd(), 'my-project');
27
console.log(exists); // true or false
28
29
// Check if configuration file exists
30
const hasConfig = checkProjectExists('/path/to/project', 'jslib.json');
31
```
32
33
### Directory Operations
34
35
Copy, create, and remove directories with comprehensive error handling.
36
37
```javascript { .api }
38
/**
39
* Copy directory and all contents from source to destination
40
* @param from - Source directory path
41
* @param to - Destination directory path
42
* @param options - Copy options (optional)
43
*/
44
function copyDir(from: string, to: string, options?: object): void;
45
46
/**
47
* Remove directory and all contents
48
* @param dirPath - Directory path to remove
49
*/
50
function deleteDir(dirPath: string): void;
51
```
52
53
### File Operations
54
55
Copy, read, and manipulate individual files with template processing support.
56
57
```javascript { .api }
58
/**
59
* Copy file from source to destination
60
* @param from - Source file path
61
* @param to - Destination file path
62
* @param opt - Copy options with cover flag
63
*/
64
function copyFile(from: string, to: string, opt?: {cover: boolean}): void;
65
66
/**
67
* Copy template file with variable substitution
68
* @param from - Source template file path (.tmpl extension)
69
* @param to - Destination file path
70
* @param data - Template variables for substitution
71
* @param opt - Copy options with cover flag
72
*/
73
function copyTmpl(from: string, to: string, data?: object, opt?: {cover: boolean}): void;
74
75
/**
76
* Remove file if it exists
77
* @param filePath - File path to remove
78
*/
79
function deleteFile(filePath: string): void;
80
```
81
82
**Usage Examples:**
83
84
```javascript
85
const util = require('@js-lib/cli/util/copy');
86
87
// Copy regular file
88
util.copyFile('/source/file.js', '/dest/file.js', { cover: true });
89
90
// Process template with variables
91
util.copyTmpl('/templates/package.json.tmpl', '/project/package.json', {
92
name: 'my-project',
93
version: '1.0.0',
94
author: 'John Doe'
95
});
96
```
97
98
### Template Processing
99
100
Process template files with variable substitution using the template_js library.
101
102
```javascript { .api }
103
/**
104
* Read and process template file with variable substitution
105
* @param from - Template file path
106
* @param data - Variables for template substitution
107
* @returns Processed template content as string
108
*/
109
function readTmpl(from: string, data?: object): string;
110
111
/**
112
* Read and parse JSON file
113
* @param from - JSON file path
114
* @returns Parsed JSON object
115
*/
116
function readJSON(from: string): object;
117
```
118
119
**Usage Examples:**
120
121
```javascript
122
const util = require('@js-lib/cli/util/copy');
123
124
// Process template file
125
const content = util.readTmpl('/templates/README.md.tmpl', {
126
projectName: 'My Awesome Project',
127
author: 'John Doe',
128
year: new Date().getFullYear()
129
});
130
131
// Read JSON configuration
132
const config = util.readJSON('/project/jslib.json');
133
```
134
135
### JSON Manipulation
136
137
Merge, update, and manipulate JSON files programmatically.
138
139
```javascript { .api }
140
/**
141
* Merge object into existing JSON file
142
* @param object - Object to merge into JSON file
143
* @param to - Path to JSON file to update
144
*/
145
function mergeObj2JSON(object: object, to: string): void;
146
147
/**
148
* Merge JSON file into another JSON file
149
* @param from - Source JSON file path
150
* @param to - Destination JSON file path
151
*/
152
function mergeJSON2JSON(from: string, to: string): void;
153
154
/**
155
* Process template file as JSON and merge into target JSON file
156
* @param from - Template JSON file path (.tmpl extension)
157
* @param to - Destination JSON file path
158
* @param data - Template variables for substitution
159
*/
160
function mergeTmpl2JSON(from: string, to: string, data?: object): void;
161
162
/**
163
* Delete specified keys from JSON file
164
* @param keysObj - Object structure defining keys to delete
165
* @param to - Path to JSON file to modify
166
*/
167
function deleteJSONKeys(keysObj: object, to: string): void;
168
```
169
170
**Usage Examples:**
171
172
```javascript
173
const util = require('@js-lib/cli/util/copy');
174
175
// Merge object into package.json
176
util.mergeObj2JSON({
177
scripts: {
178
test: 'mocha',
179
build: 'rollup -c'
180
},
181
devDependencies: {
182
mocha: '^10.0.0'
183
}
184
}, '/project/package.json');
185
186
// Remove deprecated fields
187
util.deleteJSONKeys({
188
'jsnext:main': undefined,
189
deprecated: undefined
190
}, '/project/package.json');
191
```
192
193
### File Content Manipulation
194
195
Search, replace, and modify file contents with regex and line-based operations.
196
197
```javascript { .api }
198
/**
199
* Replace lines in file that match regex pattern
200
* @param filepath - File path to modify
201
* @param match - Regular expression to match lines
202
* @param to - Replacement text
203
*/
204
function replaceFileLine(filepath: string, match: RegExp, to: string): void;
205
206
/**
207
* Delete lines in file that match regex pattern
208
* @param filepath - File path to modify
209
* @param match - Regular expression to match lines to delete
210
*/
211
function deleteFileLine(filepath: string, match: RegExp): void;
212
213
/**
214
* Replace text in file using multiple find/replace operations
215
* @param filepath - File path to modify
216
* @param replacerList - Array of replacement operations
217
*/
218
function replaceFileText(filepath: string, replacerList: Array<{
219
from: RegExp | string;
220
to: string | Function;
221
}>): void;
222
223
/**
224
* Insert text into file at specified line
225
* @param text - Text to insert
226
* @param filepath - File path to modify (created if doesn't exist)
227
* @param line - Line number to insert at (-1 for end of file)
228
*/
229
function insertText2File(text: string, filepath: string, line?: number): void;
230
```
231
232
**Usage Examples:**
233
234
```javascript
235
const util = require('@js-lib/cli/util/copy');
236
237
// Replace version line in file
238
util.replaceFileLine('/project/VERSION', /^version:/, 'version: 2.0.0');
239
240
// Complex text replacements
241
util.replaceFileText('/project/config.js', [
242
{
243
from: /const VERSION = '.*?'/,
244
to: "const VERSION = '2.0.0'"
245
},
246
{
247
from: 'oldFunctionName',
248
to: 'newFunctionName'
249
}
250
]);
251
252
// Add line to end of file
253
util.insertText2File('export default MyClass;', '/project/index.js');
254
```
255
256
### Logging Utilities
257
258
Console logging with colored output for better CLI user experience.
259
260
```javascript { .api }
261
/**
262
* Initialize enhanced console logging with colored output
263
* Adds console.success method with green text
264
* Enhances console.error with red text
265
* Enhances console.warn with orange text
266
* Enhances console.info with blue text
267
*/
268
function init(): void;
269
```
270
271
**Usage Examples:**
272
273
```javascript
274
const log = require('@js-lib/cli/util/log');
275
276
// Initialize enhanced logging
277
log.init();
278
279
// Use enhanced console methods
280
console.success('Project created successfully!');
281
console.error('Build failed!');
282
console.warn('Using deprecated feature');
283
console.info('Starting build process...');
284
```
285
286
## Types
287
288
```javascript { .api }
289
// File copy options
290
interface CopyOptions {
291
cover?: boolean; // Whether to overwrite existing files (default: true)
292
}
293
294
// Text replacement operation
295
interface TextReplacer {
296
from: RegExp | string; // Pattern to find
297
to: string | Function; // Replacement text or function
298
}
299
300
// Template data for variable substitution
301
interface TemplateData {
302
[key: string]: any; // Template variables
303
}
304
```