index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var fs = require('fs')
  2. var path = require('path')
  3. var os = require('os')
  4. // Workaround to fix webpack's build warnings: 'the request of a dependency is an expression'
  5. var runtimeRequire = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require // eslint-disable-line
  6. var abi = process.versions.modules // TODO: support old node where this is undef
  7. var runtime = isElectron() ? 'electron' : 'node'
  8. var arch = os.arch()
  9. var platform = os.platform()
  10. module.exports = load
  11. function load (dir) {
  12. return runtimeRequire(load.path(dir))
  13. }
  14. load.path = function (dir) {
  15. dir = path.resolve(dir || '.')
  16. try {
  17. var name = runtimeRequire(path.join(dir, 'package.json')).name.toUpperCase().replace(/-/g, '_')
  18. if (process.env[name + '_PREBUILD']) dir = process.env[name + '_PREBUILD']
  19. } catch (err) {}
  20. var release = getFirst(path.join(dir, 'build/Release'), matchBuild)
  21. if (release) return release
  22. var debug = getFirst(path.join(dir, 'build/Debug'), matchBuild)
  23. if (debug) return debug
  24. var prebuild = getFirst(path.join(dir, 'prebuilds/' + platform + '-' + arch), matchPrebuild)
  25. if (prebuild) return prebuild
  26. var napiRuntime = getFirst(path.join(dir, 'prebuilds/' + platform + '-' + arch), matchNapiRuntime)
  27. if (napiRuntime) return napiRuntime
  28. var napi = getFirst(path.join(dir, 'prebuilds/' + platform + '-' + arch), matchNapi)
  29. if (napi) return napi
  30. throw new Error('No native build was found for runtime=' + runtime + ' abi=' + abi + ' platform=' + platform + ' arch=' + arch)
  31. }
  32. function getFirst (dir, filter) {
  33. try {
  34. var files = fs.readdirSync(dir).filter(filter)
  35. return files[0] && path.join(dir, files[0])
  36. } catch (err) {
  37. return null
  38. }
  39. }
  40. function matchNapiRuntime (name) {
  41. return name === runtime + '-napi.node'
  42. }
  43. function matchNapi (name) {
  44. return name === 'node-napi.node'
  45. }
  46. function matchPrebuild (name) {
  47. var parts = name.split('-')
  48. return parts[0] === runtime && parts[1] === abi + '.node'
  49. }
  50. function matchBuild (name) {
  51. return /\.node$/.test(name)
  52. }
  53. function isElectron () {
  54. if (process.versions && process.versions.electron) return true
  55. if (process.env.ELECTRON_RUN_AS_NODE) return true
  56. return typeof window !== 'undefined' && window.process && window.process.type === 'renderer'
  57. }