check-disk-space 2.1.0 → 3.2.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,33 +1,53 @@
1
1
  # Check disk space
2
2
 
3
- [![Travis](https://img.shields.io/travis/Alex-D/check-disk-space.svg)](https://travis-ci.org/Alex-D/check-disk-space)
4
- [![License MIT](https://img.shields.io/github/license/Alex-D/check-disk-space.svg)](LICENCE)
5
- [![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
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)
6
+
7
+
8
+ ## Introduction
9
+
10
+ Light multi-platform disk space checker without third party for Node.js.
11
+
12
+ - Works on Linux, macOS and Windows
13
+ - Take care of mounting points on unix-like systems
14
+ - No dependencies
15
+ - TypeScript support
16
+
6
17
 
7
18
  ## Install
8
19
 
9
20
  `npm install check-disk-space`
10
21
 
22
+
11
23
  ## Usage
12
24
 
13
25
  ```js
14
- const checkDiskSpace = require('check-disk-space')
26
+ // ES
27
+ import checkDiskSpace from 'check-disk-space'
28
+
29
+ // CommonJS
30
+ const checkDiskSpace = require('check-disk-space').default
15
31
 
16
32
  // On Windows
17
33
  checkDiskSpace('C:/blabla/bla').then((diskSpace) => {
18
34
  console.log(diskSpace)
19
35
  // {
36
+ // diskPath: 'C:',
20
37
  // free: 12345678,
21
38
  // size: 98756432
22
39
  // }
40
+ // Note: `free` and `size` are in bytes
23
41
  })
24
42
 
25
43
  // On Linux or macOS
26
44
  checkDiskSpace('/mnt/mygames').then((diskSpace) => {
27
45
  console.log(diskSpace)
28
46
  // {
47
+ // diskPath: '/',
29
48
  // free: 12345678,
30
49
  // size: 98756432
31
50
  // }
51
+ // Note: `free` and `size` are in bytes
32
52
  })
33
53
  ```
@@ -0,0 +1,157 @@
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 path = require('path');
8
+
9
+ class InvalidPathError extends Error {
10
+ constructor(message) {
11
+ super(message);
12
+ this.name = 'InvalidPathError';
13
+ // Set the prototype explicitly.
14
+ Object.setPrototypeOf(this, InvalidPathError.prototype);
15
+ }
16
+ }
17
+
18
+ class NoMatchError extends Error {
19
+ constructor(message) {
20
+ super(message);
21
+ this.name = 'NoMatchError';
22
+ // Set the prototype explicitly.
23
+ Object.setPrototypeOf(this, NoMatchError.prototype);
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Get the first existing parent path
29
+ *
30
+ * @param directoryPath - The file/folder path from where we want to know disk space
31
+ * @param dependencies - Dependencies container
32
+ */
33
+ function getFirstExistingParentPath(directoryPath, dependencies) {
34
+ let parentDirectoryPath = directoryPath;
35
+ let parentDirectoryFound = dependencies.fsExistsSync(parentDirectoryPath);
36
+ while (!parentDirectoryFound) {
37
+ parentDirectoryPath = dependencies.pathNormalize(parentDirectoryPath + '/..');
38
+ parentDirectoryFound = dependencies.fsExistsSync(parentDirectoryPath);
39
+ }
40
+ return parentDirectoryPath;
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
+ function checkDiskSpace(directoryPath, dependencies = {
50
+ platform: process.platform,
51
+ fsExistsSync: fs.existsSync,
52
+ pathNormalize: path.normalize,
53
+ pathSep: path.sep,
54
+ cpExecFile: child_process.execFile,
55
+ }) {
56
+ /**
57
+ * Maps command output to a normalized object {diskPath, free, size}
58
+ *
59
+ * @param stdout - The command output
60
+ * @param filter - To filter drives (only used for win32)
61
+ * @param mapping - Map between column index and normalized column name
62
+ * @param coefficient - The size coefficient to get bytes instead of kB
63
+ */
64
+ function mapOutput(stdout, filter, mapping, coefficient) {
65
+ const parsed = stdout.trim().split('\n').slice(1).map(line => {
66
+ return line.trim().split(/\s+(?=[\d/])/);
67
+ });
68
+ const filtered = parsed.filter(filter);
69
+ if (filtered.length === 0) {
70
+ throw new NoMatchError();
71
+ }
72
+ const diskData = filtered[0];
73
+ return {
74
+ diskPath: diskData[mapping.diskPath],
75
+ free: parseInt(diskData[mapping.free], 10) * coefficient,
76
+ size: parseInt(diskData[mapping.size], 10) * coefficient,
77
+ };
78
+ }
79
+ /**
80
+ * Run the command and do common things between win32 and unix
81
+ *
82
+ * @param cmd - The command to execute
83
+ * @param filter - To filter drives (only used for win32)
84
+ * @param mapping - Map between column index and normalized column name
85
+ * @param coefficient - The size coefficient to get bytes instead of kB
86
+ */
87
+ function check(cmd, filter, mapping, coefficient = 1) {
88
+ return new Promise((resolve, reject) => {
89
+ const [file, ...args] = cmd;
90
+ /* istanbul ignore if */
91
+ if (file === undefined) {
92
+ return Promise.reject('cmd must contain at least one item');
93
+ }
94
+ dependencies.cpExecFile(file, args, (error, stdout) => {
95
+ if (error) {
96
+ reject(error);
97
+ }
98
+ try {
99
+ resolve(mapOutput(stdout, filter, mapping, coefficient));
100
+ }
101
+ catch (error2) {
102
+ reject(error2);
103
+ }
104
+ });
105
+ });
106
+ }
107
+ /**
108
+ * Build the check call for win32
109
+ *
110
+ * @param directoryPath - The file/folder path from where we want to know disk space
111
+ */
112
+ function checkWin32(directoryPath) {
113
+ if (directoryPath.charAt(1) !== ':') {
114
+ return new Promise((resolve, reject) => {
115
+ reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`));
116
+ });
117
+ }
118
+ return check(['powershell', 'Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object Caption, FreeSpace, Size'], driveData => {
119
+ // Only get the drive which match the path
120
+ const driveLetter = driveData[0];
121
+ return directoryPath.toUpperCase().startsWith(driveLetter.toUpperCase());
122
+ }, {
123
+ diskPath: 0,
124
+ free: 1,
125
+ size: 2,
126
+ });
127
+ }
128
+ /**
129
+ * Build the check call for unix
130
+ *
131
+ * @param directoryPath - The file/folder path from where we want to know disk space
132
+ */
133
+ function checkUnix(directoryPath) {
134
+ if (!dependencies.pathNormalize(directoryPath).startsWith(dependencies.pathSep)) {
135
+ return new Promise((resolve, reject) => {
136
+ reject(new InvalidPathError(`The following path is invalid (should start by ${dependencies.pathSep}): ${directoryPath}`));
137
+ });
138
+ }
139
+ const pathToCheck = getFirstExistingParentPath(directoryPath, dependencies);
140
+ return check(['df', '-Pk', '--', pathToCheck], () => true, // We should only get one line, so we did not need to filter
141
+ {
142
+ diskPath: 5,
143
+ free: 3,
144
+ size: 1,
145
+ }, 1024);
146
+ }
147
+ // Call the right check depending on the OS
148
+ if (dependencies.platform === 'win32') {
149
+ return checkWin32(directoryPath);
150
+ }
151
+ return checkUnix(directoryPath);
152
+ }
153
+
154
+ exports.InvalidPathError = InvalidPathError;
155
+ exports.NoMatchError = NoMatchError;
156
+ exports.default = checkDiskSpace;
157
+ exports.getFirstExistingParentPath = getFirstExistingParentPath;
@@ -0,0 +1,49 @@
1
+ import { ExecFileException, ChildProcess } 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 Dependencies = {
16
+ platform: NodeJS.Platform;
17
+ fsExistsSync: typeof existsSync;
18
+ pathNormalize: typeof normalize;
19
+ pathSep: typeof sep;
20
+ cpExecFile: (file: string, args: ReadonlyArray<string> | undefined | null, callback: (error: ExecFileException | null, stdout: string, stderr: string) => void) => ChildProcess;
21
+ };
22
+
23
+ /**
24
+ * Get the first existing parent path
25
+ *
26
+ * @param directoryPath - The file/folder path from where we want to know disk space
27
+ * @param dependencies - Dependencies container
28
+ */
29
+ declare function getFirstExistingParentPath(directoryPath: string, dependencies: Dependencies): string;
30
+
31
+ /**
32
+ * `free` and `size` are in bytes
33
+ */
34
+ declare type DiskSpace = {
35
+ diskPath: string;
36
+ free: number;
37
+ size: number;
38
+ };
39
+
40
+ /**
41
+ * Check disk space
42
+ *
43
+ * @param directoryPath - The file/folder path from where we want to know disk space
44
+ * @param dependencies - Dependencies container
45
+ */
46
+ declare function checkDiskSpace(directoryPath: string, dependencies?: Dependencies): Promise<DiskSpace>;
47
+
48
+ export default checkDiskSpace;
49
+ export { Dependencies, DiskSpace, InvalidPathError, NoMatchError, getFirstExistingParentPath };
@@ -0,0 +1,151 @@
1
+ import { execFile } from 'child_process';
2
+ import { existsSync } from 'fs';
3
+ import { normalize, sep } from 'path';
4
+
5
+ class InvalidPathError extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = 'InvalidPathError';
9
+ // Set the prototype explicitly.
10
+ Object.setPrototypeOf(this, InvalidPathError.prototype);
11
+ }
12
+ }
13
+
14
+ class NoMatchError extends Error {
15
+ constructor(message) {
16
+ super(message);
17
+ this.name = 'NoMatchError';
18
+ // Set the prototype explicitly.
19
+ Object.setPrototypeOf(this, NoMatchError.prototype);
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Get the first existing parent path
25
+ *
26
+ * @param directoryPath - The file/folder path from where we want to know disk space
27
+ * @param dependencies - Dependencies container
28
+ */
29
+ function getFirstExistingParentPath(directoryPath, dependencies) {
30
+ let parentDirectoryPath = directoryPath;
31
+ let parentDirectoryFound = dependencies.fsExistsSync(parentDirectoryPath);
32
+ while (!parentDirectoryFound) {
33
+ parentDirectoryPath = dependencies.pathNormalize(parentDirectoryPath + '/..');
34
+ parentDirectoryFound = dependencies.fsExistsSync(parentDirectoryPath);
35
+ }
36
+ return parentDirectoryPath;
37
+ }
38
+
39
+ /**
40
+ * Check disk space
41
+ *
42
+ * @param directoryPath - The file/folder path from where we want to know disk space
43
+ * @param dependencies - Dependencies container
44
+ */
45
+ function checkDiskSpace(directoryPath, dependencies = {
46
+ platform: process.platform,
47
+ fsExistsSync: existsSync,
48
+ pathNormalize: normalize,
49
+ pathSep: sep,
50
+ cpExecFile: execFile,
51
+ }) {
52
+ /**
53
+ * Maps command output to a normalized object {diskPath, free, size}
54
+ *
55
+ * @param stdout - The command output
56
+ * @param filter - To filter drives (only used for win32)
57
+ * @param mapping - Map between column index and normalized column name
58
+ * @param coefficient - The size coefficient to get bytes instead of kB
59
+ */
60
+ function mapOutput(stdout, filter, mapping, coefficient) {
61
+ const parsed = stdout.trim().split('\n').slice(1).map(line => {
62
+ return line.trim().split(/\s+(?=[\d/])/);
63
+ });
64
+ const filtered = parsed.filter(filter);
65
+ if (filtered.length === 0) {
66
+ throw new NoMatchError();
67
+ }
68
+ const diskData = filtered[0];
69
+ return {
70
+ diskPath: diskData[mapping.diskPath],
71
+ free: parseInt(diskData[mapping.free], 10) * coefficient,
72
+ size: parseInt(diskData[mapping.size], 10) * coefficient,
73
+ };
74
+ }
75
+ /**
76
+ * Run the command and do common things between win32 and unix
77
+ *
78
+ * @param cmd - The command to execute
79
+ * @param filter - To filter drives (only used for win32)
80
+ * @param mapping - Map between column index and normalized column name
81
+ * @param coefficient - The size coefficient to get bytes instead of kB
82
+ */
83
+ function check(cmd, filter, mapping, coefficient = 1) {
84
+ return new Promise((resolve, reject) => {
85
+ const [file, ...args] = cmd;
86
+ /* istanbul ignore if */
87
+ if (file === undefined) {
88
+ return Promise.reject('cmd must contain at least one item');
89
+ }
90
+ dependencies.cpExecFile(file, args, (error, stdout) => {
91
+ if (error) {
92
+ reject(error);
93
+ }
94
+ try {
95
+ resolve(mapOutput(stdout, filter, mapping, coefficient));
96
+ }
97
+ catch (error2) {
98
+ reject(error2);
99
+ }
100
+ });
101
+ });
102
+ }
103
+ /**
104
+ * Build the check call for win32
105
+ *
106
+ * @param directoryPath - The file/folder path from where we want to know disk space
107
+ */
108
+ function checkWin32(directoryPath) {
109
+ if (directoryPath.charAt(1) !== ':') {
110
+ return new Promise((resolve, reject) => {
111
+ reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`));
112
+ });
113
+ }
114
+ return check(['powershell', 'Get-CimInstance -ClassName Win32_LogicalDisk | Select-Object Caption, FreeSpace, Size'], driveData => {
115
+ // Only get the drive which match the path
116
+ const driveLetter = driveData[0];
117
+ return directoryPath.toUpperCase().startsWith(driveLetter.toUpperCase());
118
+ }, {
119
+ diskPath: 0,
120
+ free: 1,
121
+ size: 2,
122
+ });
123
+ }
124
+ /**
125
+ * Build the check call for unix
126
+ *
127
+ * @param directoryPath - The file/folder path from where we want to know disk space
128
+ */
129
+ function checkUnix(directoryPath) {
130
+ if (!dependencies.pathNormalize(directoryPath).startsWith(dependencies.pathSep)) {
131
+ return new Promise((resolve, reject) => {
132
+ reject(new InvalidPathError(`The following path is invalid (should start by ${dependencies.pathSep}): ${directoryPath}`));
133
+ });
134
+ }
135
+ const pathToCheck = getFirstExistingParentPath(directoryPath, dependencies);
136
+ return check(['df', '-Pk', '--', pathToCheck], () => true, // We should only get one line, so we did not need to filter
137
+ {
138
+ diskPath: 5,
139
+ free: 3,
140
+ size: 1,
141
+ }, 1024);
142
+ }
143
+ // Call the right check depending on the OS
144
+ if (dependencies.platform === 'win32') {
145
+ return checkWin32(directoryPath);
146
+ }
147
+ return checkUnix(directoryPath);
148
+ }
149
+
150
+ export default checkDiskSpace;
151
+ export { InvalidPathError, NoMatchError, getFirstExistingParentPath };
package/package.json CHANGED
@@ -1,27 +1,67 @@
1
1
  {
2
2
  "name": "check-disk-space",
3
- "version": "2.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "Light multi-platform disk space checker without third party for Node.js",
5
- "main": "index.js",
6
- "engines": {
7
- "node": ">=8"
5
+ "files": [
6
+ "dist",
7
+ "README.md"
8
+ ],
9
+ "main": "./dist/check-disk-space.cjs",
10
+ "module": "./dist/check-disk-space.mjs",
11
+ "types": "./dist/check-disk-space.d.ts",
12
+ "exports": {
13
+ "import": "./dist/check-disk-space.mjs",
14
+ "require": "./dist/check-disk-space.cjs"
8
15
  },
9
- "dependencies": {},
10
- "devDependencies": {
11
- "ava": "^2.0.0",
12
- "eslint": "^5.16.0",
13
- "eslint-plugin-ava": "^7.0.0",
14
- "npm-run-all": "^4.1.5",
15
- "xo": "^0.24.0"
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"
16
26
  },
17
- "xo": {
18
- "space": true,
19
- "semicolon": false
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
+ ]
20
40
  },
21
- "scripts": {
22
- "unit-test": "ava --color",
23
- "lint": "xo",
24
- "test": "npm-run-all unit-test lint"
41
+ "engines": {
42
+ "node": ">=12"
43
+ },
44
+ "devDependencies": {
45
+ "@alex-d/eslint-config": "1.0.3",
46
+ "@istanbuljs/nyc-config-typescript": "^1.0.1",
47
+ "@rollup/plugin-typescript": "8.2.1",
48
+ "@types/node": "15.12.2",
49
+ "@typescript-eslint/eslint-plugin": "4.26.1",
50
+ "@typescript-eslint/parser": "4.26.1",
51
+ "ava": "3.15.0",
52
+ "eslint": "7.28.0",
53
+ "eslint-plugin-ava": "12.0.0",
54
+ "eslint-plugin-import": "2.23.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.51.2",
59
+ "rollup-plugin-dts": "3.0.2",
60
+ "source-map-support": "^0.5.19",
61
+ "ts-node": "^10.0.0",
62
+ "tsconfig-paths": "^3.9.0",
63
+ "tslib": "^2.3.0",
64
+ "typescript": "4.3.2"
25
65
  },
26
66
  "repository": {
27
67
  "type": "git",
@@ -33,8 +73,7 @@
33
73
  "hdd",
34
74
  "free"
35
75
  ],
36
- "types": "./typings/index.d.ts",
37
- "author": "Alex-D <contact@alex-d.fr> (http://alex-d.fr)",
76
+ "author": "Alex-D <contact@alex-d.fr> (https://alex-d.fr)",
38
77
  "license": "MIT",
39
78
  "bugs": {
40
79
  "url": "https://github.com/Alex-D/check-disk-space/issues"
package/.editorconfig DELETED
@@ -1,14 +0,0 @@
1
- # EditorConfig is awesome: http://EditorConfig.org
2
- root = true
3
-
4
- # Unix-style newlines with a newline ending every file
5
- [*]
6
- end_of_line = lf
7
- insert_final_newline = true
8
- trim_trailing_whitespace = true
9
- charset = utf-8
10
- indent_style = space
11
- indent_size = 2
12
-
13
- [*.md]
14
- trim_trailing_whitespace = false
@@ -1,4 +0,0 @@
1
- # These are supported funding model platforms
2
-
3
- github: [Alex-D]
4
- patreon: AlexandreDemode
package/.travis.yml DELETED
@@ -1,6 +0,0 @@
1
- sudo: false
2
- language: node_js
3
- node_js:
4
- - '12'
5
- - '10'
6
- - '8'
package/index.js DELETED
@@ -1,154 +0,0 @@
1
- 'use strict'
2
-
3
- const {exec} = require('child_process')
4
- const fs = require('fs')
5
- const path = require('path')
6
- const util = require('util')
7
-
8
- // Create some errors
9
- const InvalidPathError = function (message) {
10
- Error.captureStackTrace(this, this.constructor)
11
- this.name = 'InvalidPathError'
12
- this.message = message || ''
13
- }
14
-
15
- util.inherits(InvalidPathError, Error)
16
-
17
- const NoMatchError = function (message) {
18
- Error.captureStackTrace(this, this.constructor)
19
- this.name = 'NoMatchError'
20
- this.message = message || ''
21
- }
22
-
23
- util.inherits(NoMatchError, Error)
24
-
25
- /**
26
- * Maps command output to a normalized object {free, size}
27
- *
28
- * @param {String} stdout - The command output
29
- * @param {Function} filter - To filter drives (only used for win32)
30
- * @param {Object} mapping - Map between column index and normalized column name
31
- * @param {Number} coefficient - The size coefficient to get bytes instead of kB
32
- * @return {Object} - {free, size} normalized object
33
- */
34
- function mapOutput(stdout, filter, mapping, coefficient = 1) {
35
- const parsed = stdout.trim().split('\n').slice(1).map(line => {
36
- return line.trim().split(/\s+(?=[\d/])/)
37
- })
38
-
39
- let filtered = parsed.filter(filter)
40
-
41
- if (filtered.length === 0) {
42
- throw new NoMatchError()
43
- }
44
-
45
- filtered = filtered[0]
46
-
47
- return {
48
- diskPath: filtered[mapping.diskPath],
49
- free: parseInt(filtered[mapping.free], 10) * coefficient,
50
- size: parseInt(filtered[mapping.size], 10) * coefficient
51
- }
52
- }
53
-
54
- /**
55
- * Run the command and do common things between win32 and unix
56
- *
57
- * @param {String} cmd - The command to execute
58
- * @param {Function} filter - To filter drives (only used for win32)
59
- * @param {Object} mapping - Map between column index and normalized column name
60
- * @param {Number} coefficient - The size coefficient to get bytes instead of kB
61
- * @return {Promise} -
62
- */
63
- function check(cmd, filter, mapping, coefficient = 1) {
64
- return new Promise((resolve, reject) => {
65
- exec(cmd, (error, stdout) => {
66
- if (error) {
67
- reject(error)
68
- }
69
-
70
- try {
71
- resolve(mapOutput(stdout, filter, mapping, coefficient))
72
- } catch (error2) {
73
- reject(error2)
74
- }
75
- })
76
- })
77
- }
78
-
79
- /**
80
- * Build the check call for win32
81
- *
82
- * @param {String} directoryPath - The file/folder path from where we want to know disk space
83
- * @return {Promise} -
84
- */
85
- function checkWin32(directoryPath) {
86
- if (directoryPath.charAt(1) !== ':') {
87
- return new Promise((resolve, reject) => {
88
- reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`))
89
- })
90
- }
91
-
92
- return check(
93
- 'wmic logicaldisk get size,freespace,caption',
94
- driveData => {
95
- // Only get the drive which match the path
96
- const driveLetter = driveData[0]
97
- return directoryPath.startsWith(driveLetter)
98
- },
99
- {
100
- diskPath: 0,
101
- free: 1,
102
- size: 2
103
- }
104
- )
105
- }
106
-
107
- /**
108
- * Build the check call for unix
109
- *
110
- * @param {String} directoryPath - The file/folder path from where we want to know disk space
111
- * @return {Promise} -
112
- */
113
- function checkUnix(directoryPath) {
114
- if (!path.normalize(directoryPath).startsWith(path.sep)) {
115
- return new Promise((resolve, reject) => {
116
- reject(new InvalidPathError(`The following path is invalid (should start by ${path.sep}): ${directoryPath}`))
117
- })
118
- }
119
-
120
- return check(
121
- `df -Pk "${module.exports.getFirstExistingParentPath(directoryPath)}"`,
122
- () => true, // We should only get one line, so we did not need to filter
123
- {
124
- diskPath: 5,
125
- free: 3,
126
- size: 1
127
- },
128
- 1024 // We get sizes in kB, we need to convert that to bytes
129
- )
130
- }
131
-
132
- // Inject the right check depending on the OS
133
- module.exports = (process.platform === 'win32') ? checkWin32 : checkUnix
134
-
135
- /**
136
- * Get the first existing parent path
137
- *
138
- * @param {String} directoryPath - The file/folder path from where we want to know disk space
139
- * @returns {String} - The first existing parent path
140
- */
141
- module.exports.getFirstExistingParentPath = directoryPath => {
142
- let parentDirectoryPath = directoryPath
143
- let parentDirectoryFound = fs.existsSync(parentDirectoryPath)
144
-
145
- while (!parentDirectoryFound) {
146
- parentDirectoryPath = path.normalize(parentDirectoryPath + '/..')
147
- parentDirectoryFound = fs.existsSync(parentDirectoryPath)
148
- }
149
-
150
- return parentDirectoryPath
151
- }
152
-
153
- module.exports.InvalidPathError = InvalidPathError
154
- module.exports.NoMatchError = NoMatchError
package/test.js DELETED
@@ -1,205 +0,0 @@
1
- 'use strict'
2
-
3
- import test from 'ava'
4
-
5
- const platformFixtures = {
6
- win32: [
7
- {
8
- title: 'Windows XP',
9
- path: 'D:/a/long/path',
10
- execOutput: `
11
- Caption FreeSpace Size
12
- C: 627703808 10725732352
13
- D: 0 699783168
14
- E: 25851797504 107496861696
15
- F: 834660716544 2000396742656
16
- `,
17
- result: {
18
- diskPath: 'D:',
19
- free: 0,
20
- size: 699783168
21
- }
22
- },
23
- {
24
- title: 'Windows 7',
25
- path: 'C:/blah',
26
- execOutput: `
27
- Caption FreeSpace Size
28
- C: 1286164480 34359734272
29
- D: 1864638464 50925137920
30
- E:
31
- F: 77553082368 990202818560
32
- G:
33
- L:
34
- `,
35
- result: {
36
- diskPath: 'C:',
37
- free: 1286164480,
38
- size: 34359734272
39
- }
40
- },
41
- {
42
- title: 'Windows 8',
43
- path: 'D:/MyGames',
44
- execOutput: `
45
- Caption FreeSpace Size
46
- C: 498562174976 539028877312
47
- D: 0 59494400
48
- `,
49
- result: {
50
- diskPath: 'D:',
51
- free: 0,
52
- size: 59494400
53
- }
54
- },
55
- {
56
- title: 'Windows 10',
57
- path: 'C:/User/toto',
58
- execOutput: `
59
- Caption FreeSpace Size
60
- C: 159345410048 171204145152
61
- D: 0 4001759232
62
- `,
63
- result: {
64
- diskPath: 'C:',
65
- free: 159345410048,
66
- size: 171204145152
67
- }
68
- }
69
- ],
70
- linux: [
71
- {
72
- title: 'bananian',
73
- path: '/dev',
74
- execOutput: `
75
- Filesystem 1K-blocks Used Available Use% Mounted on
76
- devtmpfs 447624 0 447624 0% /dev
77
- `,
78
- result: {
79
- diskPath: '/dev',
80
- free: 447624 * 1024,
81
- size: 447624 * 1024
82
- }
83
- },
84
- {
85
- title: 'Ubuntu',
86
- path: '/run/user/1000',
87
- execOutput: `
88
- Filesystem 1024-blocks Used Available Capacity Mounted on
89
- tmpfs 89884 8 89876 1% /run/user/1000
90
- `,
91
- result: {
92
- diskPath: '/run/user/1000',
93
- free: 89876 * 1024,
94
- size: 89884 * 1024
95
- }
96
- },
97
- {
98
- title: 'Ubuntu: russian locale',
99
- path: '/media/Games',
100
- execOutput: `
101
- Файл.система 1024-блоков Использовано Доступно Вместимость Cмонтировано в
102
- /dev/sdc 240234168 188729228 39278628 83% /media/Games
103
- `,
104
- result: {
105
- diskPath: '/media/Games',
106
- free: 39278628 * 1024,
107
- size: 240234168 * 1024
108
- }
109
- }
110
- ],
111
- darwin: [
112
- {
113
- title: 'macOS',
114
- path: '/home/jacquie',
115
- execOutput: `
116
- Filesystem 1024-blocks Used Available Capacity Mounted on
117
- /dev/disk0s2 145961032 20678788 125026244 15% /home
118
- `,
119
- result: {
120
- diskPath: '/home',
121
- free: 125026244 * 1024,
122
- size: 145961032 * 1024
123
- }
124
- }
125
- ]
126
- }
127
-
128
- function mockCheckDiskSpace(platform, fixture) {
129
- // Clean some required paths
130
- delete require.cache[require.resolve('.')]
131
-
132
- // Forces the platform for test purposes
133
- Object.defineProperty(process, 'platform', {value: platform})
134
-
135
- // Mock child_process.exec
136
- require('child_process').exec = (cmd, callback) => {
137
- process.nextTick(() => {
138
- callback(fixture.execError, fixture.execOutput)
139
- })
140
- }
141
-
142
- return require('.')
143
- }
144
-
145
- function mockGetFirstExistingParentPath(existingDirectoryPath) {
146
- // Clean some required paths
147
- delete require.cache[require.resolve('.')]
148
-
149
- // Forces the platform for test purposes
150
- Object.defineProperty(process, 'platform', {value: 'linux'})
151
-
152
- // Mock child_process.exec
153
- require('fs').existsSync = directoryPath => directoryPath === existingDirectoryPath
154
-
155
- return require('.').getFirstExistingParentPath
156
- }
157
-
158
- Object.keys(platformFixtures).forEach(platform => {
159
- platformFixtures[platform].forEach(fixture => {
160
- test(`${platform}: ${fixture.title}`, async t => {
161
- const checkDiskSpace = mockCheckDiskSpace(platform, fixture)
162
-
163
- t.deepEqual(await checkDiskSpace(fixture.path), fixture.result)
164
- })
165
- })
166
- })
167
-
168
- test('win32: path did not match any disk', async t => {
169
- const checkDiskSpace = mockCheckDiskSpace('win32', platformFixtures.win32[0])
170
- const error = await t.throwsAsync(checkDiskSpace('Z:/shouldfail'))
171
- t.is(error.name, 'NoMatchError')
172
- })
173
-
174
- test('win32: invalid path', async t => {
175
- const checkDiskSpace = mockCheckDiskSpace('win32', platformFixtures.win32[0])
176
- const error = await t.throwsAsync(checkDiskSpace('an invalid path'))
177
- t.is(error.name, 'InvalidPathError')
178
- })
179
-
180
- test('unix: invalid path', async t => {
181
- const checkDiskSpace = mockCheckDiskSpace('linux', platformFixtures.linux[0])
182
- const error = await t.throwsAsync(checkDiskSpace('an invalid path'))
183
- t.is(error.name, 'InvalidPathError')
184
- })
185
-
186
- test('exec has an error', async t => {
187
- const fixture = JSON.parse(JSON.stringify(platformFixtures.win32[0]))
188
- fixture.execError = new Error('some error')
189
-
190
- const checkDiskSpace = mockCheckDiskSpace('win32', fixture)
191
- const error = await t.throwsAsync(checkDiskSpace('C:/something'))
192
- t.is(error.message, 'some error')
193
- })
194
-
195
- test('unix: get first existing parent path', t => {
196
- const parentPath = '/home/Lisa'
197
- const getFirstExistingParentPath = mockGetFirstExistingParentPath(parentPath)
198
- t.is(getFirstExistingParentPath('/home/Lisa/games/Ankama/Dofus'), parentPath)
199
- })
200
-
201
- test('unix: get first parent can be the path itself', t => {
202
- const parentPath = '/home/Lisa'
203
- const getFirstExistingParentPath = mockGetFirstExistingParentPath(parentPath)
204
- t.is(getFirstExistingParentPath(parentPath), parentPath)
205
- })
@@ -1,77 +0,0 @@
1
- declare module "check-disk-space" {
2
- namespace checkDiskSpace {
3
- /**
4
- * The result of the disk space check
5
- */
6
- interface CheckDiskSpaceResult {
7
- /**
8
- * How much space is left
9
- */
10
- free: number;
11
- /**
12
- * The size of the path
13
- */
14
- size: number;
15
- }
16
-
17
- /**
18
- * Error for invalid path
19
- */
20
- class InvalidPathError {
21
- constructor(message: string);
22
- /**
23
- * The name of the error
24
- */
25
- name: "InvalidPathError";
26
- /**
27
- * The error message
28
- */
29
- message: string | "";
30
- }
31
-
32
- /**
33
- * Error for path which do not match the actual file system
34
- */
35
- class NoMatchError {
36
- constructor(message: any);
37
- /**
38
- * The name of the error
39
- */
40
- name: "NoMatchError";
41
- /**
42
- * The error message
43
- */
44
- message: string | "";
45
- }
46
-
47
- /**
48
- * Get the first existing parent path
49
- *
50
- * @param {string} directoryPath The file/folder path from where we want to know disk space
51
- * @returns {string} The first existing parent path
52
- */
53
- function getFirstExistingParentPath(directoryPath: string): string;
54
- }
55
-
56
- /**
57
- * Build the check call for unix or win32
58
- *
59
- * @param {string} directoryPath The file/folder path from where we want to know disk space
60
- * @return {Promise<CheckDiskSpaceResult>} The result of the check
61
- *
62
- * @example
63
- * // On Windows
64
- * const diskSpace = await checkDiskSpace('C:/blabla/bla');
65
- * console.log(diskSpace); // { free: 12345678, size: 98756432 }
66
- *
67
- * @example
68
- * const diskSpace = await checkDiskSpace('/mnt/mygames');
69
- * console.log(diskSpace); // { free: 12345678, size: 98756432 }
70
- *
71
- * @throws {NoMatchError} In case the given path does not match with the actual file system
72
- * @throws {InvalidPathError} In case the path is invalid
73
- */
74
- function checkDiskSpace(directoryPath: string): Promise<checkDiskSpace.CheckDiskSpaceResult>;
75
-
76
- export = checkDiskSpace;
77
- }
@@ -1,19 +0,0 @@
1
- import * as checkDiskSpace from 'check-disk-space';
2
-
3
- (async () => {
4
- try {
5
- const diskSpace = await checkDiskSpace('/mnt/mygames');
6
- diskSpace.free;
7
- diskSpace.size;
8
- } catch (err) {
9
- if (err instanceof checkDiskSpace.InvalidPathError) {
10
- console.error('Invalid Path Error');
11
- } else if (err instanceof checkDiskSpace.NoMatchError) {
12
- console.error('No Match Error');
13
- } else {
14
- console.error('Error');
15
- }
16
- }
17
- })();
18
-
19
- checkDiskSpace.getFirstExistingParentPath('/path');