util.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. const { CrudService } = require('naf-framework-mongoose-free/lib/service');
  3. const { BusinessError, ErrorCode } = require('naf-core').Error;
  4. const _ = require('lodash');
  5. const assert = require('assert');
  6. const os = require('os');
  7. const { execSync } = require('child_process');
  8. //
  9. class UtilService extends CrudService {
  10. constructor(ctx) {
  11. super(ctx, 'util');
  12. }
  13. async getDrives() {
  14. let lines;
  15. const osType = os.platform().toLowerCase();
  16. if (osType === 'win32') {
  17. const cmd = 'wmic logicaldisk get Caption,FreeSpace,Size,VolumeSerialNumber,Description /format:list';
  18. const cmdRes = execSync(cmd, { encoding: 'utf8' });
  19. lines = cmdRes.split('\r\r\n');
  20. } else {
  21. const cmd = "df -P | awk 'NR > 1'";
  22. const cmdRes = execSync(cmd, { encoding: 'utf8' });
  23. lines = cmdRes.split('\n');
  24. }
  25. const data = this.changeToArray(lines);
  26. return data;
  27. }
  28. /**
  29. * 整理数据
  30. * @param {Array} lines 除去换行后的数组
  31. */
  32. changeToArray(lines) {
  33. const returnArry = [];
  34. lines = lines.filter(f => f !== '');
  35. lines = _.chunk(lines, 5);
  36. for (const line of lines) {
  37. const obj = {};
  38. for (const str of line) {
  39. const arr = str.split('=');
  40. const tag = _.head(arr);
  41. const value = _.last(arr);
  42. if (tag === 'Caption') obj.mounted = value;
  43. else if (tag === 'FreeSpace') obj.available = parseFloat(value);
  44. else if (tag === 'Size') obj.blocks = parseFloat(value);
  45. else continue;
  46. }
  47. if (obj.blocks && obj.available) {
  48. obj.used = obj.blocks - obj.available;
  49. obj.capacity = Math.round((parseFloat(obj.used) / parseFloat(obj.blocks)) * 100) + '%';
  50. }
  51. returnArry.push(obj);
  52. }
  53. return returnArry;
  54. }
  55. }
  56. module.exports = UtilService;