index.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. var path = require('path');
  3. var childProcess = require('child_process');
  4. module.exports = function (target, app, cb) {
  5. if (typeof target !== 'string') {
  6. throw new Error('Expected a `target`');
  7. }
  8. if (typeof app === 'function') {
  9. cb = app;
  10. app = null;
  11. }
  12. var cmd;
  13. var args = [];
  14. if (process.platform === 'darwin') {
  15. cmd = 'open';
  16. if (cb) {
  17. args.push('-W');
  18. }
  19. if (app) {
  20. args.push('-a', app);
  21. }
  22. } else if (process.platform === 'win32') {
  23. cmd = 'cmd';
  24. args.push('/c', 'start');
  25. target = target.replace(/&/g, '^&');
  26. if (cb) {
  27. args.push('/wait');
  28. }
  29. if (app) {
  30. args.push(app);
  31. }
  32. } else {
  33. if (app) {
  34. cmd = app;
  35. } else {
  36. // http://portland.freedesktop.org/download/xdg-utils-1.1.0-rc1.tar.gz
  37. cmd = path.join(__dirname, 'xdg-open');
  38. }
  39. }
  40. args.push(target);
  41. var opts = {};
  42. if (!cb) {
  43. // xdg-open will block the process unless stdio is ignored even if it's unref()'d
  44. opts.stdio = 'ignore';
  45. }
  46. var cp = childProcess.spawn(cmd, args, opts);
  47. if (cb) {
  48. cp.once('error', cb);
  49. cp.once('close', cb);
  50. } else {
  51. cp.unref();
  52. }
  53. };