-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulp-headerfooter.js
85 lines (68 loc) · 2.07 KB
/
gulp-headerfooter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
var through = require('through2');
var fs = require('fs');
module.exports = function(header, footer) {
// return through.obj(headerfooter);
return through.obj(function(file, encoding, next) {
headerfooter(file, header, footer, encoding, next);
});
};
module.exports.header = function(header) {
return through.obj(function(file, encoding, next) {
headerfooter(file, header, null, encoding, next);
});
};
module.exports.footer = function(footer) {
return through.obj(function(file, encoding, next) {
headerfooter(file, null, footer, encoding, next);
});
};
function headerfooter(file, header, footer, encoding, next) {
var bothDone = function() {
done(file, header, footer, next);
}
var callbackCount = 0;
checkType(header, function(err, input) {
if (err) { return next(err); }
header = input;
if (++callbackCount == 2) {
bothDone();
}
});
checkType(footer, function(err, input) {
if (err) { return next(err); }
footer = input;
if (++callbackCount == 2) {
bothDone();
}
});
}
function done(file, header, footer, next) {
var contents = [];
if (header) { contents.push(header); }
if (file.contents) { contents.push(file.contents); }
if (footer) { contents.push(footer); }
file.contents = Buffer.concat(
contents
);
next(null, file);
}
function checkType(input, done) {
if (input instanceof Buffer) {
done(null, input);
} else if (typeof input == "string") {
//Could be path or full string
fs.readFile(input, function(err, fileBuffer) {
if (err) {
//Probably doesn't exist so its a string.
done(null, new Buffer(input));
} else {
input = fileBuffer;
done(null, fileBuffer);
}
});
} else if (input == null) {
done(null, null);
} else {
done(new Error("Unknown type. Either buffer, filename or string accepted."));
}
}