check-disk-space 3.3.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,53 +1,113 @@
1
- # Check disk space
1
+ <h1 align="center">Check disk space</h1>
2
2
 
3
- [![Continue Integration](https://img.shields.io/github/workflow/status/Alex-D/check-disk-space/Continuous%20Integration?style=for-the-badge)](https://github.com/Alex-D/check-disk-space/actions/workflows/ci.yml)
4
- [![check-disk-space on npm](https://img.shields.io/npm/v/check-disk-space?style=for-the-badge)](https://www.npmjs.com/package/check-disk-space)
5
- [![License MIT](https://img.shields.io/github/license/Alex-D/check-disk-space.svg?style=for-the-badge)](LICENSE)
3
+ <p align="center">
4
+ <a href="https://github.com/Alex-D/check-disk-space/actions/workflows/test.yml"><img src="https://img.shields.io/github/actions/workflow/status/Alex-D/check-disk-space/test.yml?style=for-the-badge" alt="Minimized & gzipped size ~1kb" /></a>
5
+ <a href="https://bundlejs.com/?q=check-disk-space"><img src="https://img.shields.io/bundlejs/size/check-disk-space.svg?style=for-the-badge" alt="Minimized & gzipped size ~1kb" /></a>
6
+ <a href="https://npmx.dev/package/check-disk-space"><img src="https://img.shields.io/npm/dm/check-disk-space.svg?color=blue&label=npm%20downloads&style=for-the-badge" alt="Downloads" /></a>
7
+ <a href="https://github.com/Alex-D/check-disk-space/blob/main/LICENSE"><img src="https://img.shields.io/npm/l/check-disk-space.svg?color=blue&style=for-the-badge" alt="MIT Licence" /></a>
8
+ </p>
6
9
 
10
+ <h2 align="center">Supporting check-disk-space</h2>
11
+
12
+ `check-disk-space` is an MIT-licensed open source project and completely free to use.
13
+ You can support its ongoing development by being a backer or a sponsor:
14
+
15
+ - [Become a backer or sponsor on Patreon](https://www.patreon.com/alexandredemode)
16
+ - [One-time donation via PayPal](https://www.paypal.me/demodealexandre/20eur)
17
+
18
+ ---
7
19
 
8
20
  ## Introduction
9
21
 
10
- Light multi-platform disk space checker without third party for Node.js.
22
+ A light multi-platform disk space checker without any third party compatible with Node.js, Bun and Deno.
11
23
 
12
- - Works on Linux, macOS and Windows
24
+ - Works on **Linux**, **macOS** and **Windows**
13
25
  - Take care of mounting points on unix-like systems
14
- - No dependencies
26
+ - Zero dependencies
15
27
  - TypeScript support
16
28
 
17
-
18
29
  ## Install
19
30
 
20
- `npm install check-disk-space`
21
-
31
+ | Package manager | Command |
32
+ | --------------- | ------------------------------------- |
33
+ | Vite+ | `vp add check-disk-space` |
34
+ | pnpm | `pnpm add check-disk-space` |
35
+ | npm | `npm install check-disk-space --save` |
36
+ | yarn | `yarn add check-disk-space` |
37
+ | bun | `bun add check-disk-space` |
38
+ | deno | `deno add npm:check-disk-space` |
22
39
 
23
40
  ## Usage
24
41
 
25
42
  ```js
26
- // ES
27
- import checkDiskSpace from 'check-disk-space'
43
+ import { checkDiskSpace } from "check-disk-space";
44
+ // Or with require
45
+ const { checkDiskSpace } = require("check-disk-space");
28
46
 
29
- // CommonJS
30
- const checkDiskSpace = require('check-disk-space').default
47
+ let yourPath = "";
31
48
 
32
49
  // On Windows
33
- checkDiskSpace('C:/blabla/bla').then((diskSpace) => {
34
- console.log(diskSpace)
35
- // {
36
- // diskPath: 'C:',
37
- // free: 12345678,
38
- // size: 98756432
39
- // }
40
- // Note: `free` and `size` are in bytes
41
- })
50
+ yourPath = "C:/your/path";
42
51
 
43
52
  // On Linux or macOS
44
- checkDiskSpace('/mnt/mygames').then((diskSpace) => {
45
- console.log(diskSpace)
46
- // {
47
- // diskPath: '/',
48
- // free: 12345678,
49
- // size: 98756432
50
- // }
51
- // Note: `free` and `size` are in bytes
52
- })
53
+ yourPath = "/mnt/mydisk";
54
+
55
+ checkDiskSpace(yourPath).then((diskSpace) => {
56
+ console.log(diskSpace);
57
+ // {
58
+ // diskPath: 'C:', (or '/' on Linux/macOS)
59
+ // free: 12345678,
60
+ // size: 98756432
61
+ // }
62
+ // Note: `free` and `size` are in bytes
63
+ });
64
+ ```
65
+
66
+ ### Input
67
+
68
+ - `directoryPath` (string)
69
+ - Must be a valid path depending on the OS
70
+ - Can be a non-existent directory: the lib will automatically search the first existing parent folder to find the right disk to check
71
+
72
+ ### Output
73
+
74
+ - `diskPath` (string)
75
+ - on Windows, it's always the disk letter
76
+ - on UNIX like, it depends on the mount path of the disk, so it's not necessarily `'/'`
77
+ - `free` (number)
78
+ - in bytes
79
+ - available space on the disk on which the path to check is stored on
80
+ - `size` (number)
81
+ - in bytes
82
+ - total size of the disk on which the path to check is stored on
83
+
84
+ ## Migrating from v3.x
85
+
86
+ Migrates to ESM and does not use `default` export anymore.
87
+
88
+ ```diff
89
+ - import checkDiskSpace from "check-disk-space";
90
+ + import { checkDiskSpace } from "check-disk-space";
53
91
  ```
92
+
93
+ ```diff
94
+ - const checkDiskSpace = require("check-disk-space").default;
95
+ + import { checkDiskSpace } from "check-disk-space";
96
+ ```
97
+
98
+ ## Compatibility
99
+
100
+ All of this is fully tested in the CI.
101
+
102
+ ### Supported engines
103
+
104
+ - Node 18+
105
+ - Bun 1.3+
106
+ - Deno 2.5+ (needs `sys`, `read`, `env` and `run` access)
107
+
108
+ ### Operating Systems
109
+
110
+ - UNIX like, based on the `df` output
111
+ - Linux
112
+ - macOS
113
+ - Windows 7+, based on PowerShell 3 or `wmic` depending on the version and user's rights
@@ -0,0 +1,58 @@
1
+ import { access } from "node:fs/promises";
2
+ import { normalize, sep } from "node:path";
3
+ //#region src/errors/invalidPathError.d.ts
4
+ declare class InvalidPathError extends Error {
5
+ name: string;
6
+ constructor(message?: string);
7
+ }
8
+ //#endregion
9
+ //#region src/errors/noMatchError.d.ts
10
+ declare class NoMatchError extends Error {
11
+ name: string;
12
+ constructor(message?: string);
13
+ }
14
+ //#endregion
15
+ //#region src/types/dependencies.d.ts
16
+ type Dependencies = {
17
+ platform: NodeJS.Platform;
18
+ release: string;
19
+ fsAccess: typeof access;
20
+ pathNormalize: typeof normalize;
21
+ pathSep: typeof sep;
22
+ cpExecFile: (file: string, args: ReadonlyArray<string> | undefined | null, options: {
23
+ windowsHide: true;
24
+ }) => Promise<{
25
+ stdout: string;
26
+ stderr: string;
27
+ }>;
28
+ };
29
+ //#endregion
30
+ //#region src/functions/getFirstExistingParentPath.d.ts
31
+ /**
32
+ * Get the first existing parent path
33
+ *
34
+ * @param directoryPath - The file/folder path from where we want to know disk space
35
+ * @param dependencies - Dependencies container
36
+ */
37
+ declare function getFirstExistingParentPath(directoryPath: string, dependencies: Dependencies): Promise<string>;
38
+ //#endregion
39
+ //#region src/types/diskSpace.d.ts
40
+ /**
41
+ * `free` and `size` are in bytes
42
+ */
43
+ type DiskSpace = {
44
+ diskPath: string;
45
+ free: number;
46
+ size: number;
47
+ };
48
+ //#endregion
49
+ //#region src/index.d.ts
50
+ /**
51
+ * Check disk space
52
+ *
53
+ * @param directoryPath - The file/folder path from where we want to know disk space
54
+ * @param dependencies - Dependencies container
55
+ */
56
+ declare function checkDiskSpace(directoryPath: string, dependencies?: Dependencies): Promise<DiskSpace>;
57
+ //#endregion
58
+ export { type Dependencies, type DiskSpace, InvalidPathError, NoMatchError, checkDiskSpace, getFirstExistingParentPath };
@@ -1,195 +1,183 @@
1
- import { execFile, execFileSync } from 'child_process';
2
- import { existsSync } from 'fs';
3
- import { release } from 'os';
4
- import { normalize, sep } from 'path';
5
-
6
- class InvalidPathError extends Error {
7
- constructor(message) {
8
- super(message);
9
- this.name = 'InvalidPathError';
10
- // Set the prototype explicitly.
11
- Object.setPrototypeOf(this, InvalidPathError.prototype);
12
- }
13
- }
14
-
15
- class NoMatchError extends Error {
16
- constructor(message) {
17
- super(message);
18
- this.name = 'NoMatchError';
19
- // Set the prototype explicitly.
20
- Object.setPrototypeOf(this, NoMatchError.prototype);
21
- }
1
+ import { execFile } from "node:child_process";
2
+ import { access } from "node:fs/promises";
3
+ import { release } from "node:os";
4
+ import { normalize, sep } from "node:path";
5
+ import { platform } from "node:process";
6
+ import { promisify } from "node:util";
7
+ //#region src/errors/invalidPathError.ts
8
+ var InvalidPathError = class InvalidPathError extends Error {
9
+ name = "InvalidPathError";
10
+ constructor(message) {
11
+ super(message);
12
+ Object.setPrototypeOf(this, InvalidPathError.prototype);
13
+ }
14
+ };
15
+ //#endregion
16
+ //#region src/errors/noMatchError.ts
17
+ var NoMatchError = class NoMatchError extends Error {
18
+ name = "NoMatchError";
19
+ constructor(message) {
20
+ super(message);
21
+ Object.setPrototypeOf(this, NoMatchError.prototype);
22
+ }
23
+ };
24
+ //#endregion
25
+ //#region src/functions/isDirectoryExisting.ts
26
+ /**
27
+ * Tells if directory exists
28
+ *
29
+ * @param directoryPath - The file/folder path
30
+ * @param dependencies - Dependencies container
31
+ */
32
+ async function isDirectoryExisting(directoryPath, dependencies) {
33
+ try {
34
+ await dependencies.fsAccess(directoryPath);
35
+ return Promise.resolve(true);
36
+ } catch (_error) {
37
+ return Promise.resolve(false);
38
+ }
22
39
  }
23
-
40
+ //#endregion
41
+ //#region src/functions/getFirstExistingParentPath.ts
24
42
  /**
25
- * Get the first existing parent path
26
- *
27
- * @param directoryPath - The file/folder path from where we want to know disk space
28
- * @param dependencies - Dependencies container
29
- */
30
- function getFirstExistingParentPath(directoryPath, dependencies) {
31
- let parentDirectoryPath = directoryPath;
32
- let parentDirectoryFound = dependencies.fsExistsSync(parentDirectoryPath);
33
- while (!parentDirectoryFound) {
34
- parentDirectoryPath = dependencies.pathNormalize(parentDirectoryPath + '/..');
35
- parentDirectoryFound = dependencies.fsExistsSync(parentDirectoryPath);
36
- }
37
- return parentDirectoryPath;
43
+ * Get the first existing parent path
44
+ *
45
+ * @param directoryPath - The file/folder path from where we want to know disk space
46
+ * @param dependencies - Dependencies container
47
+ */
48
+ async function getFirstExistingParentPath(directoryPath, dependencies) {
49
+ let parentDirectoryPath = directoryPath;
50
+ let parentDirectoryFound = await isDirectoryExisting(parentDirectoryPath, dependencies);
51
+ while (!parentDirectoryFound) {
52
+ const newParentDirectoryPath = dependencies.pathNormalize(parentDirectoryPath + "/..");
53
+ if (parentDirectoryPath === newParentDirectoryPath || newParentDirectoryPath === ".") return Promise.reject(new NoMatchError("Unable to find an existing parent path."));
54
+ parentDirectoryPath = newParentDirectoryPath;
55
+ parentDirectoryFound = await isDirectoryExisting(parentDirectoryPath, dependencies);
56
+ }
57
+ return parentDirectoryPath;
38
58
  }
39
-
59
+ //#endregion
60
+ //#region src/functions/hasPowerShell3.ts
40
61
  /**
41
- * Tell if PowerShell 3 is available based on Windows version
42
- *
43
- * Note: 6.* is Windows 7
44
- * Note: PowerShell 3 is natively available since Windows 8
45
- *
46
- * @param release - OS Release number
47
- */
48
- function hasPowerShell3(dependencies) {
49
- const major = parseInt(dependencies.release.split('.')[0], 10);
50
- if (major > 6) {
51
- try {
52
- dependencies.cpExecFileSync('powershell');
53
- return true;
54
- }
55
- catch (err) {
56
- return false;
57
- }
58
- }
59
- else {
60
- return false;
61
- }
62
+ * Tell if PowerShell 3 is available based on Windows version
63
+ *
64
+ * Note: 6.* is Windows 7
65
+ * Note: PowerShell 3 is natively available since Windows 8
66
+ *
67
+ * @param dependencies - Dependencies Injection Container
68
+ */
69
+ async function hasPowerShell3(dependencies) {
70
+ if (parseInt(dependencies.release.split(".")[0], 10) <= 6) return false;
71
+ try {
72
+ await dependencies.cpExecFile("where", ["powershell"], { windowsHide: true });
73
+ return true;
74
+ } catch (_error) {
75
+ return false;
76
+ }
62
77
  }
63
-
78
+ //#endregion
79
+ //#region src/index.ts
64
80
  /**
65
- * Check disk space
66
- *
67
- * @param directoryPath - The file/folder path from where we want to know disk space
68
- * @param dependencies - Dependencies container
69
- */
81
+ * Check disk space
82
+ *
83
+ * @param directoryPath - The file/folder path from where we want to know disk space
84
+ * @param dependencies - Dependencies container
85
+ */
70
86
  function checkDiskSpace(directoryPath, dependencies = {
71
- platform: process.platform,
72
- release: release(),
73
- fsExistsSync: existsSync,
74
- pathNormalize: normalize,
75
- pathSep: sep,
76
- cpExecFile: execFile,
77
- cpExecFileSync: execFileSync,
87
+ platform,
88
+ release: release(),
89
+ fsAccess: access,
90
+ pathNormalize: normalize,
91
+ pathSep: sep,
92
+ cpExecFile: promisify(execFile)
78
93
  }) {
79
- // Note: This function contains other functions in order
80
- // to wrap them in a common context and make unit tests easier
81
- /**
82
- * Maps command output to a normalized object {diskPath, free, size}
83
- *
84
- * @param stdout - The command output
85
- * @param filter - To filter drives (only used for win32)
86
- * @param mapping - Map between column index and normalized column name
87
- * @param coefficient - The size coefficient to get bytes instead of kB
88
- */
89
- function mapOutput(stdout, filter, mapping, coefficient) {
90
- const parsed = stdout.trim().split('\n').slice(1).map(line => {
91
- return line.trim().split(/\s+(?=[\d/])/);
92
- });
93
- const filtered = parsed.filter(filter);
94
- if (filtered.length === 0) {
95
- throw new NoMatchError();
96
- }
97
- const diskData = filtered[0];
98
- return {
99
- diskPath: diskData[mapping.diskPath],
100
- free: parseInt(diskData[mapping.free], 10) * coefficient,
101
- size: parseInt(diskData[mapping.size], 10) * coefficient,
102
- };
103
- }
104
- /**
105
- * Run the command and do common things between win32 and unix
106
- *
107
- * @param cmd - The command to execute
108
- * @param filter - To filter drives (only used for win32)
109
- * @param mapping - Map between column index and normalized column name
110
- * @param coefficient - The size coefficient to get bytes instead of kB
111
- */
112
- function check(cmd, filter, mapping, coefficient = 1) {
113
- return new Promise((resolve, reject) => {
114
- const [file, ...args] = cmd;
115
- /* istanbul ignore if */
116
- if (file === undefined) {
117
- return Promise.reject(new Error('cmd must contain at least one item'));
118
- }
119
- dependencies.cpExecFile(file, args, (error, stdout) => {
120
- if (error) {
121
- reject(error);
122
- }
123
- try {
124
- resolve(mapOutput(stdout, filter, mapping, coefficient));
125
- }
126
- catch (error2) {
127
- reject(error2);
128
- }
129
- });
130
- });
131
- }
132
- /**
133
- * Build the check call for win32
134
- *
135
- * @param directoryPath - The file/folder path from where we want to know disk space
136
- */
137
- function checkWin32(directoryPath) {
138
- if (directoryPath.charAt(1) !== ':') {
139
- return new Promise((resolve, reject) => {
140
- reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`));
141
- });
142
- }
143
- const powershellCmd = [
144
- 'powershell',
145
- 'Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object Caption, FreeSpace, Size',
146
- ];
147
- const wmicCmd = [
148
- 'wmic',
149
- 'logicaldisk',
150
- 'get',
151
- 'size,freespace,caption',
152
- ];
153
- const cmd = hasPowerShell3(dependencies) ? powershellCmd : wmicCmd;
154
- return check(cmd, driveData => {
155
- // Only get the drive which match the path
156
- const driveLetter = driveData[0];
157
- return directoryPath.toUpperCase().startsWith(driveLetter.toUpperCase());
158
- }, {
159
- diskPath: 0,
160
- free: 1,
161
- size: 2,
162
- });
163
- }
164
- /**
165
- * Build the check call for unix
166
- *
167
- * @param directoryPath - The file/folder path from where we want to know disk space
168
- */
169
- function checkUnix(directoryPath) {
170
- if (!dependencies.pathNormalize(directoryPath).startsWith(dependencies.pathSep)) {
171
- return new Promise((resolve, reject) => {
172
- reject(new InvalidPathError(`The following path is invalid (should start by ${dependencies.pathSep}): ${directoryPath}`));
173
- });
174
- }
175
- const pathToCheck = getFirstExistingParentPath(directoryPath, dependencies);
176
- return check([
177
- 'df',
178
- '-Pk',
179
- '--',
180
- pathToCheck,
181
- ], () => true, // We should only get one line, so we did not need to filter
182
- {
183
- diskPath: 5,
184
- free: 3,
185
- size: 1,
186
- }, 1024);
187
- }
188
- // Call the right check depending on the OS
189
- if (dependencies.platform === 'win32') {
190
- return checkWin32(directoryPath);
191
- }
192
- return checkUnix(directoryPath);
94
+ /**
95
+ * Maps command output to a normalized object {diskPath, free, size}
96
+ *
97
+ * @param stdout - The command output
98
+ * @param filter - To filter drives (only used for win32)
99
+ * @param mapping - Map between column index and normalized column name
100
+ * @param coefficient - The size coefficient to get bytes instead of kB
101
+ */
102
+ function mapOutput(stdout, filter, mapping, coefficient) {
103
+ const parsed = stdout.split("\n").map((line) => line.trim()).filter((line) => line.length !== 0).slice(1).map((line) => line.split(/\s+(?=[\d/])/));
104
+ const filtered = parsed.filter(filter);
105
+ if (filtered.length === 0) {
106
+ let errorContext = "No disk matches the path.";
107
+ if (parsed.length === 0) errorContext = "Nothing was returned by the command.";
108
+ throw new NoMatchError(errorContext);
109
+ }
110
+ const columnsCount = parsed.reduce((maxColumnCount, currentLine) => {
111
+ return Math.max(currentLine.length, maxColumnCount);
112
+ }, 0);
113
+ const diskData = filtered[0];
114
+ const indexOffset = diskData.length - columnsCount;
115
+ return {
116
+ diskPath: diskData[mapping.diskPath + indexOffset],
117
+ free: parseInt(diskData[mapping.free + indexOffset], 10) * coefficient,
118
+ size: parseInt(diskData[mapping.size + indexOffset], 10) * coefficient
119
+ };
120
+ }
121
+ /**
122
+ * Run the command and do common things between win32 and Unix
123
+ *
124
+ * @param cmd - The command to execute
125
+ * @param filter - To filter drives (only used for win32)
126
+ * @param mapping - Map between column index and normalized column name
127
+ * @param coefficient - The size coefficient to get bytes instead of kB
128
+ */
129
+ async function check(cmd, filter, mapping, coefficient = 1) {
130
+ const [file, ...args] = cmd;
131
+ /* istanbul ignore if */
132
+ if (file === void 0) return Promise.reject(/* @__PURE__ */ new Error("cmd must contain at least one item"));
133
+ try {
134
+ const { stdout } = await dependencies.cpExecFile(file, args, { windowsHide: true });
135
+ return mapOutput(stdout, filter, mapping, coefficient);
136
+ } catch (error) {
137
+ return Promise.reject(error);
138
+ }
139
+ }
140
+ /**
141
+ * Build the check call for win32
142
+ *
143
+ * @param directoryPath - The file/folder path from where we want to know disk space
144
+ */
145
+ async function checkWin32(directoryPath) {
146
+ if (directoryPath.charAt(1) !== ":") return Promise.reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`));
147
+ return check(await hasPowerShell3(dependencies) ? ["powershell", "Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object Caption, FreeSpace, Size"] : [
148
+ "wmic",
149
+ "logicaldisk",
150
+ "get",
151
+ "size,freespace,caption"
152
+ ], (driveData) => {
153
+ const driveLetter = driveData[0];
154
+ return directoryPath.toUpperCase().startsWith(driveLetter.toUpperCase());
155
+ }, {
156
+ diskPath: 0,
157
+ free: 1,
158
+ size: 2
159
+ });
160
+ }
161
+ /**
162
+ * Build the check call for Unix
163
+ *
164
+ * @param directoryPath - The file/folder path from where we want to know disk space
165
+ */
166
+ async function checkUnix(directoryPath) {
167
+ if (!dependencies.pathNormalize(directoryPath).startsWith(dependencies.pathSep)) return Promise.reject(new InvalidPathError(`The following path is invalid (should start by ${dependencies.pathSep}): ${directoryPath}`));
168
+ return check([
169
+ "df",
170
+ "-Pk",
171
+ "--",
172
+ await getFirstExistingParentPath(directoryPath, dependencies)
173
+ ], () => true, {
174
+ diskPath: 5,
175
+ free: 3,
176
+ size: 1
177
+ }, 1024);
178
+ }
179
+ if (dependencies.platform === "win32") return checkWin32(directoryPath);
180
+ return checkUnix(directoryPath);
193
181
  }
194
-
195
- export { InvalidPathError, NoMatchError, checkDiskSpace as default, getFirstExistingParentPath };
182
+ //#endregion
183
+ export { InvalidPathError, NoMatchError, checkDiskSpace, getFirstExistingParentPath };
package/package.json CHANGED
@@ -1,82 +1,55 @@
1
1
  {
2
2
  "name": "check-disk-space",
3
- "version": "3.3.1",
3
+ "version": "4.0.0",
4
4
  "description": "Light multi-platform disk space checker without third party for Node.js",
5
+ "keywords": [
6
+ "disk",
7
+ "free",
8
+ "hdd",
9
+ "space"
10
+ ],
11
+ "homepage": "https://github.com/Alex-D/check-disk-space#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/Alex-D/check-disk-space/issues"
14
+ },
15
+ "license": "MIT",
16
+ "author": "Alex-D <contact@alex-d.fr> (https://alex-d.fr)",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/Alex-D/check-disk-space.git"
20
+ },
5
21
  "files": [
6
22
  "dist",
7
23
  "README.md"
8
24
  ],
9
- "main": "./dist/check-disk-space.cjs",
10
- "module": "./dist/check-disk-space.mjs",
11
- "types": "./dist/check-disk-space.d.ts",
25
+ "type": "module",
12
26
  "exports": {
13
- "import": "./dist/check-disk-space.mjs",
14
- "require": "./dist/check-disk-space.cjs"
15
- },
16
- "scripts": {
17
- "build:lib": "rollup --config",
18
- "build:dts": "rollup --config rollup.dts.config.js",
19
- "build": "npm-run-all build:lib build:dts",
20
- "lint": "eslint . --cache",
21
- "lint:fix": "eslint --fix .",
22
- "typecheck": "tsc --noEmit",
23
- "test": "npm-run-all test:coverage lint typecheck",
24
- "test:unit": "NODE_ENV=test TS_NODE_PROJECT='tsconfig.test.json' ava",
25
- "test:coverage": "nyc --reporter=lcov --reporter=text npm run test:unit --silent"
26
- },
27
- "ava": {
28
- "files": [
29
- "test/**",
30
- "!test/__helpers__/**"
31
- ],
32
- "extensions": [
33
- "ts"
34
- ],
35
- "require": [
36
- "tsconfig-paths/register",
37
- "ts-node/register",
38
- "source-map-support/register"
39
- ]
40
- },
41
- "engines": {
42
- "node": ">=12"
27
+ ".": {
28
+ "import": "./dist/check-disk-space.mjs",
29
+ "types": "./dist/check-disk-space.d.mts"
30
+ },
31
+ "./package.json": "./package.json"
43
32
  },
44
33
  "devDependencies": {
45
- "@alex-d/eslint-config": "2.0.0",
46
- "@istanbuljs/nyc-config-typescript": "1.0.2",
47
- "@rollup/plugin-typescript": "8.3.1",
48
- "@types/node": "12.20.46",
49
- "@typescript-eslint/eslint-plugin": "5.13.0",
50
- "@typescript-eslint/parser": "5.13.0",
51
- "ava": "4.1.0",
52
- "eslint": "8.10.0",
53
- "eslint-plugin-ava": "13.2.0",
54
- "eslint-plugin-import": "2.25.4",
55
- "eslint-plugin-simple-import-sort": "7.0.0",
56
- "npm-run-all": "4.1.5",
57
- "nyc": "15.1.0",
58
- "rollup": "2.69.2",
59
- "rollup-plugin-dts": "4.2.0",
60
- "source-map-support": "0.5.21",
61
- "ts-node": "10.7.0",
62
- "tsconfig-paths": "3.13.0",
63
- "tslib": "2.3.1",
64
- "typescript": "4.6.2"
34
+ "@types/node": "^26.6.5",
35
+ "@vitest/coverage-istanbul": "^5.0.5",
36
+ "bumpp": "^12.3.0",
37
+ "typescript": "npm:typescript-native-bridge@^6.0.3-bridge.18.tsgo.7.0.2",
38
+ "vite": "npm:@voidzero-dev/vite-plus-core@1.3.0",
39
+ "vite-plus": "1.3.0"
65
40
  },
66
- "repository": {
67
- "type": "git",
68
- "url": "git+https://github.com/Alex-D/check-disk-space.git"
41
+ "devEngines": {
42
+ "packageManager": {
43
+ "name": "pnpm",
44
+ "version": "12.3.4",
45
+ "onFail": "download"
46
+ }
69
47
  },
70
- "keywords": [
71
- "disk",
72
- "space",
73
- "hdd",
74
- "free"
75
- ],
76
- "author": "Alex-D <contact@alex-d.fr> (https://alex-d.fr)",
77
- "license": "MIT",
78
- "bugs": {
79
- "url": "https://github.com/Alex-D/check-disk-space/issues"
80
- },
81
- "homepage": "https://github.com/Alex-D/check-disk-space#readme"
82
- }
48
+ "scripts": {
49
+ "build": "vp pack",
50
+ "dev": "vp pack --watch",
51
+ "dev:all": "pnpm -r --include-workspace-root --parallel dev",
52
+ "test": "vp tests",
53
+ "check": "vp check"
54
+ }
55
+ }
@@ -1,202 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- var child_process = require('child_process');
6
- var fs = require('fs');
7
- var os = require('os');
8
- var path = require('path');
9
-
10
- class InvalidPathError extends Error {
11
- constructor(message) {
12
- super(message);
13
- this.name = 'InvalidPathError';
14
- // Set the prototype explicitly.
15
- Object.setPrototypeOf(this, InvalidPathError.prototype);
16
- }
17
- }
18
-
19
- class NoMatchError extends Error {
20
- constructor(message) {
21
- super(message);
22
- this.name = 'NoMatchError';
23
- // Set the prototype explicitly.
24
- Object.setPrototypeOf(this, NoMatchError.prototype);
25
- }
26
- }
27
-
28
- /**
29
- * Get the first existing parent path
30
- *
31
- * @param directoryPath - The file/folder path from where we want to know disk space
32
- * @param dependencies - Dependencies container
33
- */
34
- function getFirstExistingParentPath(directoryPath, dependencies) {
35
- let parentDirectoryPath = directoryPath;
36
- let parentDirectoryFound = dependencies.fsExistsSync(parentDirectoryPath);
37
- while (!parentDirectoryFound) {
38
- parentDirectoryPath = dependencies.pathNormalize(parentDirectoryPath + '/..');
39
- parentDirectoryFound = dependencies.fsExistsSync(parentDirectoryPath);
40
- }
41
- return parentDirectoryPath;
42
- }
43
-
44
- /**
45
- * Tell if PowerShell 3 is available based on Windows version
46
- *
47
- * Note: 6.* is Windows 7
48
- * Note: PowerShell 3 is natively available since Windows 8
49
- *
50
- * @param release - OS Release number
51
- */
52
- function hasPowerShell3(dependencies) {
53
- const major = parseInt(dependencies.release.split('.')[0], 10);
54
- if (major > 6) {
55
- try {
56
- dependencies.cpExecFileSync('powershell');
57
- return true;
58
- }
59
- catch (err) {
60
- return false;
61
- }
62
- }
63
- else {
64
- return false;
65
- }
66
- }
67
-
68
- /**
69
- * Check disk space
70
- *
71
- * @param directoryPath - The file/folder path from where we want to know disk space
72
- * @param dependencies - Dependencies container
73
- */
74
- function checkDiskSpace(directoryPath, dependencies = {
75
- platform: process.platform,
76
- release: os.release(),
77
- fsExistsSync: fs.existsSync,
78
- pathNormalize: path.normalize,
79
- pathSep: path.sep,
80
- cpExecFile: child_process.execFile,
81
- cpExecFileSync: child_process.execFileSync,
82
- }) {
83
- // Note: This function contains other functions in order
84
- // to wrap them in a common context and make unit tests easier
85
- /**
86
- * Maps command output to a normalized object {diskPath, free, size}
87
- *
88
- * @param stdout - The command output
89
- * @param filter - To filter drives (only used for win32)
90
- * @param mapping - Map between column index and normalized column name
91
- * @param coefficient - The size coefficient to get bytes instead of kB
92
- */
93
- function mapOutput(stdout, filter, mapping, coefficient) {
94
- const parsed = stdout.trim().split('\n').slice(1).map(line => {
95
- return line.trim().split(/\s+(?=[\d/])/);
96
- });
97
- const filtered = parsed.filter(filter);
98
- if (filtered.length === 0) {
99
- throw new NoMatchError();
100
- }
101
- const diskData = filtered[0];
102
- return {
103
- diskPath: diskData[mapping.diskPath],
104
- free: parseInt(diskData[mapping.free], 10) * coefficient,
105
- size: parseInt(diskData[mapping.size], 10) * coefficient,
106
- };
107
- }
108
- /**
109
- * Run the command and do common things between win32 and unix
110
- *
111
- * @param cmd - The command to execute
112
- * @param filter - To filter drives (only used for win32)
113
- * @param mapping - Map between column index and normalized column name
114
- * @param coefficient - The size coefficient to get bytes instead of kB
115
- */
116
- function check(cmd, filter, mapping, coefficient = 1) {
117
- return new Promise((resolve, reject) => {
118
- const [file, ...args] = cmd;
119
- /* istanbul ignore if */
120
- if (file === undefined) {
121
- return Promise.reject(new Error('cmd must contain at least one item'));
122
- }
123
- dependencies.cpExecFile(file, args, (error, stdout) => {
124
- if (error) {
125
- reject(error);
126
- }
127
- try {
128
- resolve(mapOutput(stdout, filter, mapping, coefficient));
129
- }
130
- catch (error2) {
131
- reject(error2);
132
- }
133
- });
134
- });
135
- }
136
- /**
137
- * Build the check call for win32
138
- *
139
- * @param directoryPath - The file/folder path from where we want to know disk space
140
- */
141
- function checkWin32(directoryPath) {
142
- if (directoryPath.charAt(1) !== ':') {
143
- return new Promise((resolve, reject) => {
144
- reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`));
145
- });
146
- }
147
- const powershellCmd = [
148
- 'powershell',
149
- 'Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object Caption, FreeSpace, Size',
150
- ];
151
- const wmicCmd = [
152
- 'wmic',
153
- 'logicaldisk',
154
- 'get',
155
- 'size,freespace,caption',
156
- ];
157
- const cmd = hasPowerShell3(dependencies) ? powershellCmd : wmicCmd;
158
- return check(cmd, driveData => {
159
- // Only get the drive which match the path
160
- const driveLetter = driveData[0];
161
- return directoryPath.toUpperCase().startsWith(driveLetter.toUpperCase());
162
- }, {
163
- diskPath: 0,
164
- free: 1,
165
- size: 2,
166
- });
167
- }
168
- /**
169
- * Build the check call for unix
170
- *
171
- * @param directoryPath - The file/folder path from where we want to know disk space
172
- */
173
- function checkUnix(directoryPath) {
174
- if (!dependencies.pathNormalize(directoryPath).startsWith(dependencies.pathSep)) {
175
- return new Promise((resolve, reject) => {
176
- reject(new InvalidPathError(`The following path is invalid (should start by ${dependencies.pathSep}): ${directoryPath}`));
177
- });
178
- }
179
- const pathToCheck = getFirstExistingParentPath(directoryPath, dependencies);
180
- return check([
181
- 'df',
182
- '-Pk',
183
- '--',
184
- pathToCheck,
185
- ], () => true, // We should only get one line, so we did not need to filter
186
- {
187
- diskPath: 5,
188
- free: 3,
189
- size: 1,
190
- }, 1024);
191
- }
192
- // Call the right check depending on the OS
193
- if (dependencies.platform === 'win32') {
194
- return checkWin32(directoryPath);
195
- }
196
- return checkUnix(directoryPath);
197
- }
198
-
199
- exports.InvalidPathError = InvalidPathError;
200
- exports.NoMatchError = NoMatchError;
201
- exports["default"] = checkDiskSpace;
202
- exports.getFirstExistingParentPath = getFirstExistingParentPath;
@@ -1,51 +0,0 @@
1
- import { ChildProcess, ExecException } from 'child_process';
2
- import { existsSync } from 'fs';
3
- import { normalize, sep } from 'path';
4
-
5
- declare class InvalidPathError extends Error {
6
- name: string;
7
- constructor(message?: string);
8
- }
9
-
10
- declare class NoMatchError extends Error {
11
- name: string;
12
- constructor(message?: string);
13
- }
14
-
15
- declare type ExecFileException = ExecException & NodeJS.ErrnoException;
16
- declare type Dependencies = {
17
- platform: NodeJS.Platform;
18
- release: string;
19
- fsExistsSync: typeof existsSync;
20
- pathNormalize: typeof normalize;
21
- pathSep: typeof sep;
22
- cpExecFile: (file: string, args: ReadonlyArray<string> | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void) => ChildProcess;
23
- cpExecFileSync: (command: string) => Buffer;
24
- };
25
-
26
- /**
27
- * Get the first existing parent path
28
- *
29
- * @param directoryPath - The file/folder path from where we want to know disk space
30
- * @param dependencies - Dependencies container
31
- */
32
- declare function getFirstExistingParentPath(directoryPath: string, dependencies: Dependencies): string;
33
-
34
- /**
35
- * `free` and `size` are in bytes
36
- */
37
- declare type DiskSpace = {
38
- diskPath: string;
39
- free: number;
40
- size: number;
41
- };
42
-
43
- /**
44
- * Check disk space
45
- *
46
- * @param directoryPath - The file/folder path from where we want to know disk space
47
- * @param dependencies - Dependencies container
48
- */
49
- declare function checkDiskSpace(directoryPath: string, dependencies?: Dependencies): Promise<DiskSpace>;
50
-
51
- export { Dependencies, DiskSpace, InvalidPathError, NoMatchError, checkDiskSpace as default, getFirstExistingParentPath };