cmd.js 2.4 KB

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