bin.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. #!/usr/bin/env node
  2. var proc = require('child_process')
  3. var os = require('os')
  4. var path = require('path')
  5. if (!buildFromSource()) {
  6. proc.exec('node-gyp-build-test', function (err, stdout, stderr) {
  7. if (err) {
  8. if (verbose()) console.error(stderr)
  9. preinstall()
  10. }
  11. })
  12. } else {
  13. preinstall()
  14. }
  15. function build () {
  16. var win32 = os.platform() === 'win32'
  17. var args = [win32 ? 'node-gyp.cmd' : 'node-gyp', 'rebuild']
  18. try {
  19. var pkg = require('node-gyp/package.json')
  20. args = [
  21. process.execPath,
  22. path.join(require.resolve('node-gyp/package.json'), '..', typeof pkg.bin === 'string' ? pkg.bin : pkg.bin['node-gyp']),
  23. 'rebuild'
  24. ]
  25. } catch (_) {}
  26. proc.spawn(args[0], args.slice(1), { stdio: 'inherit', shell: win32, windowsHide: true }).on('exit', function (code) {
  27. if (code || !process.argv[3]) process.exit(code)
  28. exec(process.argv[3]).on('exit', function (code) {
  29. process.exit(code)
  30. })
  31. })
  32. }
  33. function preinstall () {
  34. if (!process.argv[2]) return build()
  35. exec(process.argv[2]).on('exit', function (code) {
  36. if (code) process.exit(code)
  37. build()
  38. })
  39. }
  40. function exec (cmd) {
  41. if (process.platform !== 'win32') {
  42. var shell = os.platform() === 'android' ? 'sh' : true
  43. return proc.spawn(cmd, [], {
  44. shell,
  45. stdio: 'inherit'
  46. })
  47. }
  48. return proc.spawn(cmd, [], {
  49. windowsVerbatimArguments: true,
  50. stdio: 'inherit',
  51. shell: true,
  52. windowsHide: true
  53. })
  54. }
  55. function buildFromSource () {
  56. return hasFlag('--build-from-source') || process.env.npm_config_build_from_source === 'true'
  57. }
  58. function verbose () {
  59. return hasFlag('--verbose') || process.env.npm_config_loglevel === 'verbose'
  60. }
  61. // TODO (next major): remove in favor of env.npm_config_* which works since npm
  62. // 0.1.8 while npm_config_argv will stop working in npm 7. See npm/rfcs#90
  63. function hasFlag (flag) {
  64. if (!process.env.npm_config_argv) return false
  65. try {
  66. return JSON.parse(process.env.npm_config_argv).original.indexOf(flag) !== -1
  67. } catch (_) {
  68. return false
  69. }
  70. }