util.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. 'use strict'
  2. const cp = require('child_process')
  3. const path = require('path')
  4. const { openSync, closeSync } = require('graceful-fs')
  5. const log = require('./log')
  6. const execFile = async (...args) => new Promise((resolve) => {
  7. const child = cp.execFile(...args, (...a) => resolve(a))
  8. child.stdin.end()
  9. })
  10. async function regGetValue (key, value, addOpts) {
  11. const outReValue = value.replace(/\W/g, '.')
  12. const outRe = new RegExp(`^\\s+${outReValue}\\s+REG_\\w+\\s+(\\S.*)$`, 'im')
  13. const reg = path.join(process.env.SystemRoot, 'System32', 'reg.exe')
  14. const regArgs = ['query', key, '/v', value].concat(addOpts)
  15. log.silly('reg', 'running', reg, regArgs)
  16. const [err, stdout, stderr] = await execFile(reg, regArgs, { encoding: 'utf8' })
  17. log.silly('reg', 'reg.exe stdout = %j', stdout)
  18. if (err || stderr.trim() !== '') {
  19. log.silly('reg', 'reg.exe err = %j', err && (err.stack || err))
  20. log.silly('reg', 'reg.exe stderr = %j', stderr)
  21. if (err) {
  22. throw err
  23. }
  24. throw new Error(stderr)
  25. }
  26. const result = outRe.exec(stdout)
  27. if (!result) {
  28. log.silly('reg', 'error parsing stdout')
  29. throw new Error('Could not parse output of reg.exe')
  30. }
  31. log.silly('reg', 'found: %j', result[1])
  32. return result[1]
  33. }
  34. async function regSearchKeys (keys, value, addOpts) {
  35. for (const key of keys) {
  36. try {
  37. return await regGetValue(key, value, addOpts)
  38. } catch {
  39. continue
  40. }
  41. }
  42. }
  43. /**
  44. * Returns the first file or directory from an array of candidates that is
  45. * readable by the current user, or undefined if none of the candidates are
  46. * readable.
  47. */
  48. function findAccessibleSync (logprefix, dir, candidates) {
  49. for (let next = 0; next < candidates.length; next++) {
  50. const candidate = path.resolve(dir, candidates[next])
  51. let fd
  52. try {
  53. fd = openSync(candidate, 'r')
  54. } catch (e) {
  55. // this candidate was not found or not readable, do nothing
  56. log.silly(logprefix, 'Could not open %s: %s', candidate, e.message)
  57. continue
  58. }
  59. closeSync(fd)
  60. log.silly(logprefix, 'Found readable %s', candidate)
  61. return candidate
  62. }
  63. return undefined
  64. }
  65. module.exports = {
  66. execFile,
  67. regGetValue,
  68. regSearchKeys,
  69. findAccessibleSync
  70. }