0
# Core Task System
1
2
The core task system provides the foundation for defining and executing build tasks with prerequisites, asynchronous operations, and file dependency checking.
3
4
## Capabilities
5
6
### Task Definition
7
8
Creates a Jake Task that can have prerequisites and an action to perform.
9
10
```javascript { .api }
11
/**
12
* Creates a Jake Task
13
* @param {string} name - The name of the Task
14
* @param {string[]} [prereqs] - Prerequisites to be run before this task
15
* @param {Function} [action] - The action to perform for this task
16
* @param {Object} [opts] - Task options
17
* @param {boolean} [opts.async=false] - Perform this task asynchronously
18
* @param {number} [opts.concurrency=1] - Number of prereqs to run concurrently
19
* @returns {Task} The created task instance
20
*/
21
function task(name, prereqs, action, opts);
22
```
23
24
**Usage Examples:**
25
26
```javascript
27
// Simple task
28
desc('This is the default task.');
29
task('default', function () {
30
console.log('This is the default task.');
31
});
32
33
// Task with prerequisites
34
desc('This task has prerequisites.');
35
task('hasPrereqs', ['foo', 'bar', 'baz'], function () {
36
console.log('Ran some prereqs first.');
37
});
38
39
// Asynchronous task
40
desc('This is an asynchronous task.');
41
task('asyncTask', function () {
42
setTimeout(complete, 1000);
43
}, { async: true });
44
45
// Task with parameters from command line
46
task('greet', function (name, greeting) {
47
console.log(greeting + ', ' + name + '!');
48
});
49
// Usage: jake greet[John,Hello]
50
```
51
52
### File Task Definition
53
54
Creates a Jake FileTask that represents a file and can check modification times against prerequisites.
55
56
```javascript { .api }
57
/**
58
* Creates a Jake FileTask
59
* @param {string} name - The file path this task represents
60
* @param {string[]} [prereqs] - Prerequisites to be run before this task
61
* @param {Function} [action] - The action to create this file, if it doesn't exist
62
* @param {Object} [opts] - Task options
63
* @param {boolean} [opts.async=false] - Perform this task asynchronously
64
* @returns {FileTask} The created file task instance
65
*/
66
function file(name, prereqs, action, opts);
67
```
68
69
**Usage Examples:**
70
71
```javascript
72
// File task that compiles TypeScript
73
file('dist/app.js', ['src/app.ts'], function () {
74
jake.exec(['tsc src/app.ts --outDir dist'], function () {
75
complete();
76
});
77
}, { async: true });
78
79
// File task with multiple dependencies
80
file('build/bundle.min.js', ['build/bundle.js'], function () {
81
jake.exec(['uglifyjs build/bundle.js -o build/bundle.min.js'], function () {
82
complete();
83
});
84
}, { async: true });
85
86
// File task that only runs if source is newer
87
file('docs/api.html', ['src/**/*.js'], function () {
88
jake.exec(['jsdoc src -d docs'], function () {
89
complete();
90
});
91
}, { async: true });
92
```
93
94
### Directory Task Definition
95
96
Creates a Jake DirectoryTask that ensures a directory exists.
97
98
```javascript { .api }
99
/**
100
* Creates a Jake DirectoryTask that ensures a directory exists
101
* @param {string} name - The directory path to create
102
* @returns {DirectoryTask} The created directory task instance
103
*/
104
function directory(name);
105
```
106
107
**Usage Examples:**
108
109
```javascript
110
// Create directories for build output
111
directory('dist');
112
directory('build/assets');
113
directory('tmp/cache');
114
115
// Use directory as prerequisite
116
file('dist/app.js', ['dist', 'src/app.js'], function () {
117
// dist directory is guaranteed to exist
118
jake.cpR('src/app.js', 'dist/app.js');
119
});
120
```
121
122
### Task Description
123
124
Sets a description for the next task that will be created. The description is displayed when running `jake -T`.
125
126
```javascript { .api }
127
/**
128
* Creates a description for a Jake Task
129
* @param {string} description - The description for the Task
130
*/
131
function desc(description);
132
```
133
134
**Usage Examples:**
135
136
```javascript
137
desc('Compile all TypeScript files');
138
task('compile', ['clean'], function () {
139
jake.exec(['tsc']);
140
});
141
142
desc('Run all tests');
143
task('test', ['compile'], function () {
144
jake.exec(['mocha test/**/*.js']);
145
});
146
147
desc('Clean build directory');
148
task('clean', function () {
149
jake.rmRf('dist');
150
});
151
```
152
153
### Task Completion
154
155
Completes an asynchronous task, allowing Jake's execution to proceed to the next task.
156
157
```javascript { .api }
158
/**
159
* Completes an asynchronous task
160
* @param {Task} [task] - Specific task to complete (optional)
161
* @param {*} [value] - Return value for the task (optional)
162
*/
163
function complete(task, value);
164
```
165
166
**Usage Examples:**
167
168
```javascript
169
// Complete the current task
170
task('asyncTask', function () {
171
setTimeout(function () {
172
console.log('Async work done');
173
complete();
174
}, 1000);
175
}, { async: true });
176
177
// Complete with a return value
178
task('getData', function () {
179
fetchData(function (err, data) {
180
if (err) {
181
fail(err);
182
} else {
183
complete(null, data);
184
}
185
});
186
}, { async: true });
187
188
// Complete a specific task (for parallel execution)
189
task('parallelTask', ['taskA', 'taskB'], function () {
190
// Both taskA and taskB run in parallel
191
setTimeout(function () {
192
complete(this, 'result');
193
}.bind(this), 500);
194
}, { async: true });
195
```
196
197
### Task Failure
198
199
Causes Jake execution to abort with an error and optional exit code.
200
201
```javascript { .api }
202
/**
203
* Causes Jake execution to abort with an error
204
* @param {Error|string} err - The error to throw when aborting execution
205
* @param {number} [code] - Optional exit code for the process
206
*/
207
function fail(err, code);
208
```
209
210
**Usage Examples:**
211
212
```javascript
213
task('checkEnv', function () {
214
if (!process.env.NODE_ENV) {
215
fail('NODE_ENV environment variable is required');
216
}
217
});
218
219
task('validateConfig', function () {
220
try {
221
const config = JSON.parse(fs.readFileSync('config.json'));
222
if (!config.apiKey) {
223
fail('API key is missing from config', 1);
224
}
225
} catch (e) {
226
fail(e, 2);
227
}
228
});
229
230
// Fail with multi-line error
231
task('complexValidation', function () {
232
const errors = validateProject();
233
if (errors.length > 0) {
234
const errorMsg = 'Validation failed:\n' + errors.join('\n');
235
fail(errorMsg);
236
}
237
});
238
```
239
240
## Task Execution Patterns
241
242
### Sequential Execution
243
244
Tasks run their prerequisites in order before executing their own action:
245
246
```javascript
247
task('build', ['clean', 'compile', 'bundle'], function () {
248
console.log('Build complete');
249
});
250
// Execution order: clean → compile → bundle → build action
251
```
252
253
### Parallel Prerequisites
254
255
Use concurrency option to run prerequisites in parallel:
256
257
```javascript
258
task('test', ['unit-tests', 'integration-tests'], function () {
259
console.log('All tests complete');
260
}, { concurrency: 2 }); // Run both test tasks in parallel
261
```
262
263
### Conditional Execution
264
265
File tasks automatically check if they need to run based on modification times:
266
267
```javascript
268
file('output.txt', ['input1.txt', 'input2.txt'], function () {
269
// Only runs if input files are newer than output.txt
270
jake.exec(['cat input1.txt input2.txt > output.txt']);
271
});
272
```
273
274
### Asynchronous Task Patterns
275
276
```javascript
277
// Using callbacks
278
task('fetchData', function () {
279
https.get('https://api.example.com/data', function (res) {
280
// Process response
281
complete();
282
});
283
}, { async: true });
284
285
// Using promises
286
task('processFiles', function () {
287
processFilesAsync()
288
.then(function (result) {
289
console.log('Processing complete');
290
complete();
291
})
292
.catch(function (err) {
293
fail(err);
294
});
295
}, { async: true });
296
297
// Using async/await (Node.js 8+)
298
task('modernAsync', async function () {
299
try {
300
const result = await processFilesAsync();
301
console.log('Result:', result);
302
complete();
303
} catch (err) {
304
fail(err);
305
}
306
}, { async: true });
307
```
308
309
## Advanced Task Management
310
311
### Task Series
312
313
Creates a sequential execution function from multiple tasks that returns a Promise.
314
315
```javascript { .api }
316
/**
317
* Creates a sequential execution function from multiple tasks
318
* @param {...Function} tasks - Functions representing tasks to run in series
319
* @returns {Function} Function that returns a Promise when called
320
*/
321
function series(...tasks);
322
```
323
324
**Usage Examples:**
325
326
```javascript
327
// Define tasks as functions
328
const cleanTask = function() {
329
jake.rmRf('dist');
330
};
331
332
const buildTask = function() {
333
jake.exec(['webpack --mode=production'], { printStdout: true });
334
};
335
336
const testTask = function() {
337
jake.exec(['npm test'], { printStdout: true });
338
};
339
340
// Create series execution function
341
const buildPipeline = series(cleanTask, buildTask, testTask);
342
343
// Execute the series
344
task('pipeline', async function() {
345
await buildPipeline();
346
console.log('Pipeline complete');
347
});
348
```
349
350
### Task Timeout Configuration
351
352
Sets the global timeout for all tasks in milliseconds.
353
354
```javascript { .api }
355
/**
356
* Sets the global timeout for all tasks
357
* @param {number} timeout - Timeout in milliseconds
358
*/
359
function setTaskTimeout(timeout);
360
```
361
362
**Usage Examples:**
363
364
```javascript
365
// Set 5 minute timeout for all tasks
366
setTaskTimeout(300000);
367
368
// Set different timeout for specific environments
369
if (process.env.NODE_ENV === 'ci') {
370
setTaskTimeout(600000); // 10 minutes for CI
371
} else {
372
setTaskTimeout(120000); // 2 minutes for development
373
}
374
```
375
376
### Series Auto Prefix
377
378
Sets an automatic prefix for task names created through the series function.
379
380
```javascript { .api }
381
/**
382
* Sets an automatic prefix for series-generated task names
383
* @param {string} prefix - Prefix to add to task names
384
*/
385
function setSeriesAutoPrefix(prefix);
386
```
387
388
**Usage Examples:**
389
390
```javascript
391
// Set prefix for series tasks
392
setSeriesAutoPrefix('auto:');
393
394
const taskSeries = series(cleanTask, buildTask);
395
// Generated internal tasks will have names like 'auto:cleanTask', 'auto:buildTask'
396
```