openurl.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. var spawn = require('child_process').spawn;
  2. var command;
  3. switch(process.platform) {
  4. case 'darwin':
  5. command = 'open';
  6. break;
  7. case 'win32':
  8. command = 'explorer.exe';
  9. break;
  10. case 'linux':
  11. command = 'xdg-open';
  12. break;
  13. default:
  14. throw new Error('Unsupported platform: ' + process.platform);
  15. }
  16. /**
  17. * Error handling is deliberately minimal, as this function is to be easy to use for shell scripting
  18. *
  19. * @param url The URL to open
  20. * @param callback A function with a single error argument. Optional.
  21. */
  22. function open(url, callback) {
  23. var child = spawn(command, [url]);
  24. var errorText = "";
  25. child.stderr.setEncoding('utf8');
  26. child.stderr.on('data', function (data) {
  27. errorText += data;
  28. });
  29. child.stderr.on('end', function () {
  30. if (errorText.length > 0) {
  31. var error = new Error(errorText);
  32. if (callback) {
  33. callback(error);
  34. } else {
  35. throw error;
  36. }
  37. } else if (callback) {
  38. callback(error);
  39. }
  40. });
  41. }
  42. /**
  43. * @param fields Common fields are: "subject", "body".
  44. * Some email apps let you specify arbitrary headers here.
  45. * @param recipientsSeparator Default is ",". Use ";" for Outlook.
  46. */
  47. function mailto(recipients, fields, recipientsSeparator, callback) {
  48. recipientsSeparator = recipientsSeparator || ",";
  49. var url = "mailto:"+recipients.join(recipientsSeparator);
  50. Object.keys(fields).forEach(function (key, index) {
  51. if (index === 0) {
  52. url += "?";
  53. } else {
  54. url += "&";
  55. }
  56. url += key + "=" + encodeURIComponent(fields[key]);
  57. });
  58. open(url, callback);
  59. }
  60. exports.open = open;
  61. exports.mailto = mailto;