UNPKG

2.43 kBJavaScriptView Raw
1#!/usr/bin/env node
2var fs = require('fs');
3var JSONStream = require('JSONStream');
4var through = require('through2');
5var mkdirp = require('mkdirp-classic');
6var path = require('path');
7
8var b = require('./args')(process.argv.slice(2));
9process.stdout.on('error', process.exit);
10
11if ((b.argv._[0] === 'help' && b.argv._[1]) === 'advanced'
12|| (b.argv.h || b.argv.help) === 'advanced') {
13 return fs.createReadStream(__dirname + '/advanced.txt')
14 .pipe(process.stdout)
15 .on('close', function () { process.exit(1) })
16 ;
17}
18if (b.argv._[0] === 'help' || b.argv.h || b.argv.help
19|| (process.argv.length <= 2 && process.stdin.isTTY)) {
20 return fs.createReadStream(__dirname + '/usage.txt')
21 .pipe(process.stdout)
22 .on('close', function () { process.exit(1) })
23 ;
24}
25if (b.argv.version) {
26 return console.log(require('../package.json').version);
27}
28
29b.on('error', errorExit);
30
31if (b.argv.pack) {
32 process.stdin.pipe(b.pack()).pipe(process.stdout);
33 process.stdin.resume();
34 return;
35}
36
37if (b.argv.deps) {
38 var stringify = JSONStream.stringify();
39 stringify.pipe(process.stdout);
40 b.pipeline.get('deps').push(through.obj(
41 function (row, enc, next) { stringify.write(row); next() },
42 function () { stringify.end() }
43 ));
44 return b.bundle();
45}
46
47if (b.argv.list) {
48 b.pipeline.get('deps').push(through.obj(
49 function (row, enc, next) {
50 console.log(row.file || row.id);
51 next()
52 }
53 ));
54 return b.bundle();
55}
56
57var bundle = b.bundle();
58bundle.on('error', errorExit);
59bundle.on('end', successExit);
60
61var tmpfile;
62var outfile = b.argv.o || b.argv.outfile;
63if (outfile) {
64 mkdirp.sync(path.dirname(outfile));
65
66 // we'll output to a temp file within same filesystem, then atomically overwrite outfile once successful
67 tmpfile = outfile + ".tmp-browserify-" + Math.random().toFixed(20).slice(2)
68 bundle.pipe(fs.createWriteStream(tmpfile));
69}
70else {
71 bundle.pipe(process.stdout);
72}
73
74function errorExit(err) {
75 if (tmpfile) fs.unlink(tmpfile, function (err) {
76 if (err) /* no-op, we're already exiting unhappily… */;
77 });
78 if (err.stack) {
79 console.error(err.stack);
80 }
81 else {
82 console.error(String(err));
83 }
84 process.exit(1);
85}
86
87function successExit() {
88 if (tmpfile && outfile) fs.rename(tmpfile, outfile, function (err) {
89 if (err) errorExit(err);
90 });
91}