open.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. var exec = require('child_process').exec
  2. , path = require('path')
  3. ;
  4. /**
  5. * open a file or uri using the default application for the file type.
  6. *
  7. * @return {ChildProcess} - the child process object.
  8. * @param {string} target - the file/uri to open.
  9. * @param {string} appName - (optional) the application to be used to open the
  10. * file (for example, "chrome", "firefox")
  11. * @param {function(Error)} callback - called with null on success, or
  12. * an error object that contains a property 'code' with the exit
  13. * code of the process.
  14. */
  15. module.exports = open;
  16. function open(target, appName, callback) {
  17. var opener;
  18. if (typeof(appName) === 'function') {
  19. callback = appName;
  20. appName = null;
  21. }
  22. switch (process.platform) {
  23. case 'darwin':
  24. if (appName) {
  25. opener = 'open -a "' + escape(appName) + '"';
  26. } else {
  27. opener = 'open';
  28. }
  29. break;
  30. case 'win32':
  31. // if the first parameter to start is quoted, it uses that as the title
  32. // so we pass a blank title so we can quote the file we are opening
  33. if (appName) {
  34. opener = 'start "" "' + escape(appName) + '"';
  35. } else {
  36. opener = 'start ""';
  37. }
  38. break;
  39. default:
  40. if (appName) {
  41. opener = escape(appName);
  42. } else {
  43. // use Portlands xdg-open everywhere else
  44. opener = path.join(__dirname, './xdg-open');
  45. }
  46. break;
  47. }
  48. if (process.env.SUDO_USER) {
  49. opener = 'sudo -u ' + process.env.SUDO_USER + ' ' + opener;
  50. }
  51. return exec(opener + ' "' + escape(target) + '"', callback);
  52. }
  53. function escape(s) {
  54. return s.replace(/"/g, '\\\"');
  55. }