forked from thaggie/gulp-json-transform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (49 loc) · 1.5 KB
/
index.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
var Promise = require('promise');
var through = require('through2');
var gutil = require('gulp-util');
var PluginError = gutil.PluginError;
const PLUGIN_NAME = 'gulp-json-transform';
function jsonPromiseParse(rawStr) {
return new Promise(function(resolve, reject) {
var json;
try {
json = JSON.parse(rawStr);
} catch (e) {
return reject(new Error('Invalid JSON'));
}
resolve(json);
});
}
module.exports = function(transformFn, jsonSpace) {
if (!transformFn) {
throw new PluginError(PLUGIN_NAME, 'Missing transform function!');
}
return through.obj(function(file, enc, cb) {
var self = this;
if (file.isStream()) {
return self.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported'));
}
if (file.isBuffer()) {
var fileContent = file.contents.toString(enc);
jsonPromiseParse(fileContent)
.then(function(data){
return transformFn(data, {
path: file.path,
relative: file.relative,
base: file.base
});
})
.then(function(output) {
var isString = (typeof output === 'string');
file.contents = new Buffer(isString ? output : JSON.stringify(output, null, jsonSpace));
self.push(file);
cb();
})
.catch(function(e) {
gutil.log(PLUGIN_NAME + ':', gutil.colors.red(e.message));
self.emit('error', new PluginError(PLUGIN_NAME, e));
self.emit('end');
});
}
});
};