whichLib.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict'
  2. const checkWindows = require('./checkWindows')
  3. const lib = {
  4. mode: null,
  5. binding: null,
  6. shell: null,
  7. }
  8. function change (mode, strict) {
  9. if (checkWindows.async() === false) return
  10. switch (mode) {
  11. case 'auto':
  12. case 'binding':
  13. {
  14. if (lib.binding === null) {
  15. try {
  16. lib.binding = require('./binding')
  17. lib.mode = 'binding'
  18. } catch (error) {
  19. if (strict !== true) {
  20. lib.binding = null
  21. change('shell')
  22. } else {
  23. // For tests to know which installations could not load the binding
  24. throw error
  25. }
  26. }
  27. } else {
  28. lib.mode = 'binding'
  29. }
  30. break
  31. }
  32. case 'shell':
  33. {
  34. if (lib.shell === null) lib.shell = require('./shell')
  35. lib.mode = 'shell'
  36. break
  37. }
  38. }
  39. }
  40. function current () {
  41. return lib[lib.mode]
  42. }
  43. function run (callback) {
  44. let result
  45. try {
  46. result = callback()
  47. } catch (error) {
  48. // If binding error
  49. if (lib.mode === 'binding' && error.message === 'The specified procedure could not be found.') {
  50. change('shell')
  51. result = callback()
  52. } else {
  53. throw error
  54. }
  55. }
  56. return result
  57. }
  58. module.exports = {
  59. change,
  60. current,
  61. run,
  62. }