UNPKG

1.98 kBJavaScriptView Raw
1var Stream = require('stream')
2 , gutil = require('gulp-util')
3 , BufferStreams = require('bufferstreams')
4 , ttf2eot = require('ttf2eot')
5 , path = require('path')
6;
7
8const PLUGIN_NAME = 'gulp-ttf2eot';
9
10// File level transform function
11function ttf2eotTransform(opt) {
12 // Return a callback function handling the buffered content
13 return function(err, buf, cb) {
14
15 // Handle any error
16 if(err) {
17 cb(new gutil.PluginError(PLUGIN_NAME, err, {showStack: true}));
18 }
19
20 // Use the buffered content
21 try {
22 buf = new Buffer(ttf2eot(new Uint8Array(buf)).buffer);
23 cb(null, buf);
24 } catch(err) {
25 cb(new gutil.PluginError(PLUGIN_NAME, err, {showStack: true}));
26 }
27
28 };
29}
30
31// Plugin function
32function ttf2eotGulp(options) {
33
34 options = options || {};
35 options.ignoreExt = options.ignoreExt || false;
36
37 var stream = new Stream.Transform({objectMode: true});
38
39 stream._transform = function(file, unused, done) {
40 // When null just pass through
41 if(file.isNull()) {
42 stream.push(file); done();
43 return;
44 }
45
46 // If the ext doesn't match, pass it through
47 if((!options.ignoreExt) && '.ttf' !== path.extname(file.path)) {
48 stream.push(file); done();
49 return;
50 }
51
52 file.path = gutil.replaceExtension(file.path, ".eot");
53
54 // Buffers
55 if(file.isBuffer()) {
56 try {
57 file.contents = new Buffer(ttf2eot(
58 new Uint8Array(file.contents)
59 ).buffer);
60 } catch(err) {
61 stream.emit('error', new gutil.PluginError(PLUGIN_NAME, err, {
62 showStack: true
63 }));
64 }
65
66 // Streams
67 } else {
68 file.contents = file.contents.pipe(new BufferStreams(ttf2eotTransform()));
69 }
70
71 stream.push(file);
72 done();
73 };
74
75 return stream;
76
77};
78
79// Export the file level transform function for other plugins usage
80ttf2eotGulp.fileTransform = ttf2eotTransform;
81
82// Export the plugin main function
83module.exports = ttf2eotGulp;
84