/
asset.js
56 lines (44 loc) · 1.6 KB
/
asset.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
var fs = require( 'fs' );
var async = require( 'async' );
var mkdirp = require( 'mkdirp' );
var combine = require( 'stream-combiner' );
var path = require( 'path' );
var _ = require( 'underscore' );
module.exports = Asset;
function Asset( srcPath, type, transforms, appData ) {
this.srcPath = srcPath;
this.type = type;
this.transforms = transforms;
this.appData = appData;
}
Asset.prototype.addTransform = function( transform, prepend ) {
if( _.isUndefined( prepend ) ) prepend = false;
if( prepend ) this.transforms.unshift( transform );
else this.transforms.push( transform );
};
Asset.prototype.createReadStream = function() {
var stream = fs.createReadStream( this.srcPath );
return this._applyTransforms( stream, this.transforms );
};
Asset.prototype.writeToDisk = function( dstPath, callback ) {
var _this = this;
this.dstPath = dstPath; // save this for later
async.series( [ function( nextSeries ) {
mkdirp( path.dirname( dstPath ), nextSeries );
}, function( nextSeries ) {
var stream = _this.createReadStream();
stream.on( 'error', function( err ) {
nextSeries( new Error( 'While reading or transforming "' + _this.srcPath + '":\n' + err.message ) );
} );
stream.on( 'end', nextSeries );
stream.pipe( fs.createWriteStream( dstPath ) );
} ], callback );
};
Asset.prototype._applyTransforms = function( stream, transforms ) {
var _this = this;
if( ! transforms || transforms.length === 0 ) return stream;
var combinedStream = combine.apply( null, transforms.map( function( thisTransform ) {
return thisTransform( _this.srcPath );
} ) );
return stream.pipe( combinedStream );
};