-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
69 lines (51 loc) · 1.69 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
60
61
62
63
64
65
66
67
68
69
'use strict';
var through = require('through2'),
pluginError = require('gulp-util').PluginError;
var PLUGIN_NAME = 'gulp-native2ascii';
var stringHandler, contentsHandler;
// taken from https://github.com/yyfrankyy/native2ascii.js/blob/master/native2ascii.js
function native2ascii(str) {
var character = str.split('');
var ascii = '';
for (var i = 0; i < character.length; i++) {
var code = Number(character[i].charCodeAt(0));
if (code > 127) {
var charAscii = code.toString(16);
charAscii = new String('0000').substring(charAscii.length, 4) + charAscii;
ascii += '\\u' + charAscii;
} else {
ascii += character[i];
}
}
return ascii;
}
function ascii2native(str) {
return unescape(str.split('\\').join('%'));
}
function handleStream(contents) {
return contents.pipe(through(function (chunk, enc, callback) {
this.push(stringHandler(chunk.toString()));
callback();
}));
}
function handleBuffer(contents) {
return new Buffer(stringHandler(contents.toString()));
}
module.exports = function (options) {
return through.obj(function (file, enc, callback) {
if (file.isNull()) {
this.push(file);
return callback();
}
stringHandler = (options && options.reverse) ? ascii2native : native2ascii;
contentsHandler = file.isBuffer() ? handleBuffer : handleStream;
try {
file.contents = contentsHandler(file.contents);
} catch (err) {
this.emit('error', new pluginError(PLUGIN_NAME, err));
return callback();
}
this.push(file);
callback();
});
};