You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.1 KiB

7 years ago
  1. #!/usr/bin/env node
  2. "use strict";
  3. var childProcess = require("child_process");
  4. function opener(args, options, callback) {
  5. // http://stackoverflow.com/q/1480971/3191, but see below for Windows.
  6. var command = process.platform === "win32" ? "cmd" :
  7. process.platform === "darwin" ? "open" :
  8. "xdg-open";
  9. if (typeof args === "string") {
  10. args = [args];
  11. }
  12. if (typeof options === "function") {
  13. callback = options;
  14. options = {};
  15. }
  16. if (options && typeof options === "object" && options.command) {
  17. if (process.platform === "win32") {
  18. // *always* use cmd on windows
  19. args = [options.command].concat(args);
  20. } else {
  21. command = options.command;
  22. }
  23. }
  24. if (process.platform === "win32") {
  25. // On Windows, we really want to use the "start" command. But, the rules regarding arguments with spaces, and
  26. // escaping them with quotes, can get really arcane. So the easiest way to deal with this is to pass off the
  27. // responsibility to "cmd /c", which has that logic built in.
  28. //
  29. // Furthermore, if "cmd /c" double-quoted the first parameter, then "start" will interpret it as a window title,
  30. // so we need to add a dummy empty-string window title: http://stackoverflow.com/a/154090/3191
  31. //
  32. // Additionally, on Windows ampersand needs to be escaped when passed to "start"
  33. args = args.map(function(value) {
  34. return value.replace(/&/g, '^&');
  35. });
  36. args = ["/c", "start", '""'].concat(args);
  37. }
  38. return childProcess.execFile(command, args, options, callback);
  39. }
  40. // Export `opener` for programmatic access.
  41. // You might use this to e.g. open a website: `opener("http://google.com")`
  42. module.exports = opener;
  43. // If we're being called from the command line, just execute, using the command-line arguments.
  44. if (require.main && require.main.id === module.id) {
  45. opener(process.argv.slice(2), function (error) {
  46. if (error) {
  47. throw error;
  48. }
  49. });
  50. }