/ src / services / fsService.js
fsService.js
 1  import path from "path";
 2  import fs from "fs";
 3  import { filesystemSync } from "fs-filesystem";
 4  
 5  export class FsService {
 6    getAvailableRoots = () => {
 7      const devices = filesystemSync();
 8      var mountPoints = [];
 9      Object.keys(devices).forEach(function (key) {
10        var val = devices[key];
11        val.volumes.forEach(function (volume) {
12          const mount = volume.mountPoint;
13          if (mount != null && mount != undefined && mount.length > 0) {
14            try {
15              if (!fs.lstatSync(mount).isFile()) {
16                mountPoints.push(mount);
17              }
18            } catch {}
19          }
20        });
21      });
22  
23      if (mountPoints.length < 1) {
24        // In certain containerized environments, the devices don't reveal any
25        // useful mounts. We'll proceed under the assumption that '/' is valid here.
26        return ["/"];
27      }
28      return mountPoints;
29    };
30  
31    pathJoin = (parts) => {
32      return path.join(...parts);
33    };
34  
35    isDir = (dir) => {
36      try {
37        return fs.lstatSync(dir).isDirectory();
38      } catch {
39        return false;
40      }
41    };
42  
43    isFile = (path) => {
44      try {
45        return fs.lstatSync(path).isFile();
46      } catch {
47        return false;
48      }
49    };
50  
51    readDir = (dir) => {
52      return fs.readdirSync(dir);
53    };
54  
55    makeDir = (dir) => {
56      fs.mkdirSync(dir);
57    };
58  
59    moveDir = (oldPath, newPath) => {
60      fs.moveSync(oldPath, newPath);
61    };
62  
63    deleteDir = (dir) => {
64      fs.rmSync(dir, { recursive: true, force: true });
65    };
66  
67    readJsonFile = (filePath) => {
68      return JSON.parse(fs.readFileSync(filePath));
69    };
70  
71    readFile = (filePath) => {
72      return fs.readFileSync(filePath);
73    };
74  
75    writeJsonFile = (filePath, jsonObject) => {
76      fs.writeFileSync(filePath, JSON.stringify(jsonObject));
77    };
78  
79    writeFile = (filePath, content) => {
80      fs.writeFileSync(filePath, content);
81    };
82  
83    ensureDirExists = (dir) => {
84      if (!fs.existsSync(dir)) {
85        fs.mkdirSync(dir, { recursive: true });
86      }
87      return dir;
88    };
89  }