lrf 2 年之前
父節點
當前提交
682e4c7746
共有 2 個文件被更改,包括 59 次插入6 次删除
  1. 2 6
      app/service/disk.js
  2. 57 0
      app/service/util.js

+ 2 - 6
app/service/disk.js

@@ -14,12 +14,8 @@ class DiskService extends CrudService {
   }
 
   async diskInfo() {
-    return new Promise(resolve => {
-      d.getDrives(function(err, aDrives) {
-        aDrives = aDrives.map(i => _.omit(i, [ 'filesystem' ]));
-        resolve(aDrives);
-      });
-    });
+    const res = await this.ctx.service.util.getDrives();
+    return res;
   }
   async toDir({ route = [ '' ] } = {}) {
     const root = this.app.config.dirRoot;

+ 57 - 0
app/service/util.js

@@ -0,0 +1,57 @@
+'use strict';
+const { CrudService } = require('naf-framework-mongoose-free/lib/service');
+const { BusinessError, ErrorCode } = require('naf-core').Error;
+const _ = require('lodash');
+const assert = require('assert');
+const os = require('os');
+const { execSync } = require('child_process');
+//
+class UtilService extends CrudService {
+  constructor(ctx) {
+    super(ctx, 'util');
+  }
+  async getDrives() {
+    let lines;
+    const osType = os.platform().toLowerCase();
+    if (osType === 'win32') {
+      const cmd = 'wmic logicaldisk get Caption,FreeSpace,Size,VolumeSerialNumber,Description  /format:list';
+      const cmdRes = execSync(cmd, { encoding: 'utf8' });
+      lines = cmdRes.split('\r\r\n');
+    } else {
+      const cmd = "df -P | awk 'NR > 1'";
+      const cmdRes = execSync(cmd, { encoding: 'utf8' });
+      lines = cmdRes.split('\n');
+    }
+    const data = this.changeToArray(lines);
+    return data;
+  }
+  /**
+   * 整理数据
+   * @param {Array} lines 除去换行后的数组
+   */
+  changeToArray(lines) {
+    const returnArry = [];
+    lines = lines.filter(f => f !== '');
+    lines = _.chunk(lines, 5);
+    for (const line of lines) {
+      const obj = {};
+      for (const str of line) {
+        const arr = str.split('=');
+        const tag = _.head(arr);
+        const value = _.last(arr);
+        if (tag === 'Caption') obj.mounted = value;
+        else if (tag === 'FreeSpace') obj.available = parseFloat(value);
+        else if (tag === 'Size') obj.blocks = parseFloat(value);
+        else continue;
+      }
+      if (obj.blocks && obj.available) {
+        obj.used = obj.blocks - obj.available;
+        obj.capacity = Math.round((parseFloat(obj.used) / parseFloat(obj.blocks)) * 100) + '%';
+      }
+      returnArry.push(obj);
+    }
+    return returnArry;
+  }
+}
+
+module.exports = UtilService;