UNPKG

3.05 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3var fs = require( 'fs' );
4var path = require( 'path' );
5var outpipe = require( 'outpipe' );
6var subarg = require( 'subarg' );
7
8var nodeConsole = console;
9
10function run() {
11 var _argv = process.argv.slice( 2 );
12 var persistifyArgs = subarg( _argv, {
13 alias: {
14 'n': 'never-cache',
15 'd': 'cache-dir'
16 }
17 } );
18
19 var watch = persistifyArgs.watch;
20 var recreate = persistifyArgs.recreate;
21 var neverCache = persistifyArgs[ 'never-cache' ];
22 var cacheId = persistifyArgs[ 'cache-id' ];
23 var cacheDir = persistifyArgs[ 'cache-dir' ];
24
25 var w = require( '../' )( null, {
26 cacheId: cacheId,
27 cacheDir: cacheDir,
28 command: _argv.join( ' ' ),
29 neverCache: neverCache,
30 watch: watch,
31 recreate: recreate
32 }, process.argv.slice( 2 ) );
33
34 var outfile = w.argv.o || w.argv.outfile;
35 var verbose = w.argv.v || w.argv.verbose;
36
37 if ( w.argv.version ) {
38 nodeConsole.error( 'persistify v' + require( '../package.json' ).version +
39 ' (in ' + path.resolve( __dirname, '..' ) + ')'
40 );
41 nodeConsole.error( 'watchify v' + require( 'watchify/package.json' ).version +
42 ' (in ' + path.dirname( require.resolve( 'watchify' ) ) + ')'
43 );
44 nodeConsole.error( 'browserify v' + require( 'browserify/package.json' ).version +
45 ' (in ' + path.dirname( require.resolve( 'browserify' ) ) + ')'
46 );
47 return;
48 }
49
50 if ( !outfile ) {
51 nodeConsole.error( 'You MUST specify an outfile with -o.' );
52 process.exit( 1 ); //eslint-disable-line
53 }
54
55 var bytes, time;
56 if ( watch ) {
57 w.on( 'bytes', function ( b ) {
58 bytes = b;
59 } );
60 w.on( 'time', function ( t ) {
61 time = t;
62 } );
63 } else {
64 w.on( 'bundle:done', function ( t ) {
65 time = t;
66 } );
67 }
68
69 w.on( 'skip:cache', function ( file ) {
70 if ( !verbose ) {
71 return;
72 }
73 nodeConsole.error( 'skip file from cache:', file );
74 } );
75
76 function bundle() {
77 var didError = false;
78 var outStream = process.platform === 'win32'
79 ? fs.createWriteStream( outfile )
80 : outpipe( outfile );
81
82 var wb = w.bundle();
83 wb.on( 'error', function ( err ) {
84 nodeConsole.error( String( err ) );
85 didError = true;
86 outStream.end( 'console.error(' + JSON.stringify( String( err ) ) + ');' );
87 } );
88 wb.pipe( outStream );
89
90 outStream.on( 'error', function ( err ) {
91 nodeConsole.error( 'persistify error: ', err );
92 } );
93 outStream.on( 'close', function () {
94 if ( didError && !watch ) {
95 nodeConsole.error( 'persistify failed...' );
96 process.exit( 1 ); //eslint-disable-line
97 }
98 if ( verbose && !didError ) {
99 if ( watch ) {
100 nodeConsole.error( bytes + ' bytes written to ' + outfile
101 + ' (' + (time / 1000).toFixed( 2 ) + ' seconds)'
102 );
103 } else {
104 nodeConsole.error( 'bundle done! '
105 + ' (' + (time / 1000).toFixed( 2 ) + ' seconds)'
106 );
107 }
108 }
109
110 } );
111 }
112
113 w.on( 'update', bundle );
114 bundle();
115}
116
117run();