Repository navigation
Expand file tree
/
Copy pathdiskusage.cc
More file actions
683 lines (585 loc) · 22.2 KB
/
Copy pathdiskusage.cc
File metadata and controls
683 lines (585 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
// Native disk usage backend.
// Single-path API:
// checkSync / checkAsync / checkSyncBig / checkAsyncBig
// Enumerate-all API:
// listVolumesSync / listVolumesAsync (Number & BigInt variants)
//
// Backends:
// - Windows: GetLogicalDriveStringsW + GetDriveTypeW + GetDiskFreeSpaceExW +
// GetVolumeInformationW
// - macOS: getmntinfo(MNT_NOWAIT) -> statfs[]
// - Linux: /proc/mounts + statvfs per mount
#include <napi.h>
#include <string>
#include <vector>
#include <cstdint>
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#elif defined(__APPLE__)
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#include <sys/statvfs.h>
#include <errno.h>
#include <cstring>
#else
#include <sys/statvfs.h>
#include <errno.h>
#include <cstring>
#include <cstdio>
#include <mntent.h>
#endif
#if !defined(_WIN32)
#include <sys/stat.h>
#include <dirent.h>
#endif
namespace {
struct DiskInfo {
uint64_t available = 0;
uint64_t free = 0;
uint64_t total = 0;
};
struct VolumeInfo {
std::string mountpoint; // Win: "C:\\" *nix: "/", "/Volumes/Data"
std::string name; // Win: volume label, *nix: 同 mountpoint
std::string fs; // Win: "NTFS"/"FAT32"/..., *nix: f_fstypename / mntent type
std::string type; // "fixed" | "removable" | "network" | "cdrom" | "ramdisk" | "unknown"
std::string device; // macOS: f_mntfromname (/dev/disk3s1s1); Linux: mnt_fsname (/dev/sda1);
// Win: Volume GUID path (\\?\Volume{...}\)
bool ok = false; // 查询是否成功(如光驱无盘片时返回 ok=false)
std::string errMsg; // ok=false 时的错误描述
DiskInfo usage{};
};
struct DirSize {
uint64_t size = 0; // 所有文件字节总和
uint64_t files = 0; // 文件数
uint64_t directories = 0; // 目录数(含根目录)
};
// ------------------- Directory size query -------------------
#if defined(_WIN32)
static void WalkDirWin(const std::wstring& root, DirSize& out) {
std::vector<std::wstring> stack;
stack.push_back(root);
while (!stack.empty()) {
std::wstring dir = std::move(stack.back());
stack.pop_back();
std::wstring pattern = dir;
if (!pattern.empty() && pattern.back() != L'\\') pattern += L'\\';
pattern += L'*';
WIN32_FIND_DATAW fd;
HANDLE hFind = FindFirstFileW(pattern.c_str(), &fd);
if (hFind == INVALID_HANDLE_VALUE) continue;
do {
if (fd.cFileName[0] == L'.' && (fd.cFileName[1] == L'\0' ||
(fd.cFileName[1] == L'.' && fd.cFileName[2] == L'\0')))
continue;
// 跳过符号链接 / junctions / reparse points(避免循环)
if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
continue;
if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
out.directories++;
std::wstring sub = dir;
if (!sub.empty() && sub.back() != L'\\') sub += L'\\';
sub += fd.cFileName;
stack.push_back(std::move(sub));
} else {
out.files++;
out.size += (static_cast<uint64_t>(fd.nFileSizeHigh) << 32) |
static_cast<uint64_t>(fd.nFileSizeLow);
}
} while (FindNextFileW(hFind, &fd));
FindClose(hFind);
}
}
static std::string QueryDirectorySize(const std::string& path, DirSize& out) {
int wlen = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
if (wlen <= 0) return "Invalid path encoding";
std::wstring wpath(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, &wpath[0], wlen);
wpath.resize(wlen - 1); // 去掉 MultiByteToWideChar 写入的末尾 \0,避免后续拼接路径时 null 卡在中间
DWORD attr = GetFileAttributesW(wpath.c_str());
if (attr == INVALID_FILE_ATTRIBUTES)
return "Path not found: " + path;
if (!(attr & FILE_ATTRIBUTE_DIRECTORY))
return "Not a directory: " + path;
out.directories = 1;
WalkDirWin(wpath, out);
return {};
}
#else // POSIX
static void WalkDirPosix(const std::string& root, DirSize& out) {
std::vector<std::string> stack;
stack.push_back(root);
while (!stack.empty()) {
std::string dir = std::move(stack.back());
stack.pop_back();
DIR* d = opendir(dir.c_str());
if (!d) continue;
struct dirent* ent;
while ((ent = readdir(d)) != nullptr) {
if (ent->d_name[0] == '.' && (ent->d_name[1] == '\0' ||
(ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
continue;
std::string full = dir;
if (!full.empty() && full.back() != '/') full += '/';
full += ent->d_name;
struct stat st;
if (lstat(full.c_str(), &st) != 0) continue;
// 跳过符号链接(避免循环和重复计数)
if (S_ISLNK(st.st_mode)) continue;
if (S_ISDIR(st.st_mode)) {
out.directories++;
stack.push_back(std::move(full));
} else if (S_ISREG(st.st_mode)) {
out.files++;
out.size += static_cast<uint64_t>(st.st_size);
}
}
closedir(d);
}
}
static std::string QueryDirectorySize(const std::string& path, DirSize& out) {
struct stat st;
if (lstat(path.c_str(), &st) != 0)
return std::string("Cannot stat path: ") + std::strerror(errno);
if (!S_ISDIR(st.st_mode))
return "Not a directory: " + path;
out.directories = 1;
WalkDirPosix(path, out);
return {};
}
#endif
// ------------------- Single-path query -------------------
std::string QueryDisk(const std::string& path, DiskInfo& out) {
#if defined(_WIN32)
int wlen = MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, nullptr, 0);
if (wlen <= 0) return "Invalid path encoding";
std::wstring wpath(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, path.c_str(), -1, &wpath[0], wlen);
ULARGE_INTEGER avail{}, total{}, free{};
if (!GetDiskFreeSpaceExW(wpath.c_str(), &avail, &total, &free)) {
DWORD err = GetLastError();
return "GetDiskFreeSpaceExW failed, error code: " + std::to_string(err);
}
out.available = static_cast<uint64_t>(avail.QuadPart);
out.total = static_cast<uint64_t>(total.QuadPart);
out.free = static_cast<uint64_t>(free.QuadPart);
return {};
#else
struct statvfs s{};
if (statvfs(path.c_str(), &s) != 0) {
return std::string("statvfs failed: ") + std::strerror(errno);
}
const uint64_t frsize = static_cast<uint64_t>(s.f_frsize ? s.f_frsize : s.f_bsize);
out.total = frsize * static_cast<uint64_t>(s.f_blocks);
out.free = frsize * static_cast<uint64_t>(s.f_bfree);
out.available = frsize * static_cast<uint64_t>(s.f_bavail);
return {};
#endif
}
// ------------------- List all volumes -------------------
#if defined(_WIN32)
static std::string Utf16ToUtf8(const wchar_t* w) {
if (!w) return {};
int len = WideCharToMultiByte(CP_UTF8, 0, w, -1, nullptr, 0, nullptr, nullptr);
if (len <= 1) return {};
std::string s(len - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, w, -1, &s[0], len, nullptr, nullptr);
return s;
}
static const char* DriveTypeName(UINT t) {
switch (t) {
case DRIVE_REMOVABLE: return "removable";
case DRIVE_FIXED: return "fixed";
case DRIVE_REMOTE: return "network";
case DRIVE_CDROM: return "cdrom";
case DRIVE_RAMDISK: return "ramdisk";
default: return "unknown";
}
}
static std::vector<VolumeInfo> ListVolumes() {
std::vector<VolumeInfo> result;
DWORD need = GetLogicalDriveStringsW(0, nullptr);
if (need == 0) return result;
std::wstring buf(need, L'\0');
DWORD got = GetLogicalDriveStringsW(need, &buf[0]);
if (got == 0) return result;
// buf 是 "C:\\\0D:\\\0...\0\0" 形式
size_t i = 0;
while (i < buf.size() && buf[i] != L'\0') {
const wchar_t* root = &buf[i];
size_t rlen = wcslen(root);
VolumeInfo v;
v.mountpoint = Utf16ToUtf8(root);
UINT dt = GetDriveTypeW(root);
v.type = DriveTypeName(dt);
// Volume GUID 路径(同一物理卷在多个盘符挂载时 GUID 相同)
wchar_t guid[64] = {0};
if (GetVolumeNameForVolumeMountPointW(root, guid, 64)) {
v.device = Utf16ToUtf8(guid);
}
wchar_t volName[MAX_PATH + 1] = {0};
wchar_t fsName[MAX_PATH + 1] = {0};
DWORD serial = 0, maxComp = 0, flags = 0;
// SetErrorMode 防止光驱无盘片弹窗
UINT oldMode = SetErrorMode(SEM_FAILCRITICALERRORS);
BOOL viOk = GetVolumeInformationW(root, volName, MAX_PATH, &serial,
&maxComp, &flags, fsName, MAX_PATH);
if (viOk) {
v.name = Utf16ToUtf8(volName);
v.fs = Utf16ToUtf8(fsName);
}
ULARGE_INTEGER avail{}, total{}, freeBytes{};
if (GetDiskFreeSpaceExW(root, &avail, &total, &freeBytes)) {
v.usage.available = avail.QuadPart;
v.usage.total = total.QuadPart;
v.usage.free = freeBytes.QuadPart;
v.ok = true;
} else {
DWORD ec = GetLastError();
v.ok = false;
v.errMsg = "GetDiskFreeSpaceExW failed, error code: " + std::to_string(ec);
}
SetErrorMode(oldMode);
if (v.name.empty()) v.name = v.mountpoint;
result.push_back(std::move(v));
i += rlen + 1; // 跳过当前串以及 \0
}
return result;
}
#elif defined(__APPLE__)
static std::vector<VolumeInfo> ListVolumes() {
std::vector<VolumeInfo> result;
struct statfs* mounts = nullptr;
int n = getmntinfo(&mounts, MNT_NOWAIT);
if (n <= 0 || !mounts) return result;
for (int i = 0; i < n; i++) {
const struct statfs& m = mounts[i];
VolumeInfo v;
v.mountpoint = m.f_mntonname;
v.name = m.f_mntonname;
v.fs = m.f_fstypename;
v.device = m.f_mntfromname;
// 简单分类:网络挂载 vs 本地
if ((m.f_flags & MNT_LOCAL) == 0) v.type = "network";
else if (std::strcmp(m.f_fstypename, "devfs") == 0 ||
std::strcmp(m.f_fstypename, "autofs") == 0)
v.type = "unknown";
else v.type = "fixed";
// 用 f_bsize(块字节数)直接算字节
const uint64_t bs = m.f_bsize ? m.f_bsize : 4096;
v.usage.total = bs * static_cast<uint64_t>(m.f_blocks);
v.usage.free = bs * static_cast<uint64_t>(m.f_bfree);
v.usage.available = bs * static_cast<uint64_t>(m.f_bavail);
v.ok = true;
result.push_back(std::move(v));
}
return result;
}
#else // Linux
static std::vector<VolumeInfo> ListVolumes() {
std::vector<VolumeInfo> result;
FILE* fp = setmntent("/proc/mounts", "r");
if (!fp) fp = setmntent("/etc/mtab", "r");
if (!fp) return result;
struct mntent ent{};
char buf[4096];
while (getmntent_r(fp, &ent, buf, sizeof(buf))) {
// 过滤掉虚拟/伪文件系统,避免 df 一样的噪音
const char* fst = ent.mnt_type ? ent.mnt_type : "";
if (!fst[0]) continue;
static const char* kSkip[] = {
"proc", "sysfs", "cgroup", "cgroup2", "devpts", "tmpfs", "devtmpfs",
"mqueue", "debugfs", "tracefs", "securityfs", "pstore", "bpf",
"configfs", "hugetlbfs", "fusectl", "binfmt_misc", "autofs",
"rpc_pipefs", "nsfs", "overlay", "squashfs", "ramfs"
};
bool skip = false;
for (const char* s : kSkip) if (std::strcmp(fst, s) == 0) { skip = true; break; }
if (skip) continue;
VolumeInfo v;
v.mountpoint = ent.mnt_dir ? ent.mnt_dir : "";
v.name = v.mountpoint;
v.fs = fst;
v.device = ent.mnt_fsname ? ent.mnt_fsname : "";
if (std::strncmp(fst, "nfs", 3) == 0 || std::strcmp(fst, "cifs") == 0 ||
std::strcmp(fst, "smbfs") == 0 || std::strcmp(fst, "smb3") == 0 ||
std::strcmp(fst, "fuse.sshfs") == 0)
v.type = "network";
else if (std::strcmp(fst, "iso9660") == 0 || std::strcmp(fst, "udf") == 0)
v.type = "cdrom";
else
v.type = "fixed";
struct statvfs s{};
if (statvfs(v.mountpoint.c_str(), &s) == 0) {
const uint64_t fr = s.f_frsize ? s.f_frsize : s.f_bsize;
v.usage.total = fr * static_cast<uint64_t>(s.f_blocks);
v.usage.free = fr * static_cast<uint64_t>(s.f_bfree);
v.usage.available = fr * static_cast<uint64_t>(s.f_bavail);
v.ok = true;
} else {
v.ok = false;
v.errMsg = std::string("statvfs failed: ") + std::strerror(errno);
}
result.push_back(std::move(v));
}
endmntent(fp);
return result;
}
#endif
// ------------------- Napi result builders -------------------
Napi::Object BuildResult(Napi::Env env, const DiskInfo& info) {
Napi::Object obj = Napi::Object::New(env);
obj.Set("available", Napi::Number::New(env, static_cast<double>(info.available)));
obj.Set("free", Napi::Number::New(env, static_cast<double>(info.free)));
obj.Set("total", Napi::Number::New(env, static_cast<double>(info.total)));
return obj;
}
Napi::Object BuildResultBig(Napi::Env env, const DiskInfo& info) {
Napi::Object obj = Napi::Object::New(env);
obj.Set("available", Napi::BigInt::New(env, info.available));
obj.Set("free", Napi::BigInt::New(env, info.free));
obj.Set("total", Napi::BigInt::New(env, info.total));
return obj;
}
Napi::Value BuildVolumes(Napi::Env env, const std::vector<VolumeInfo>& vols, bool big) {
Napi::Array arr = Napi::Array::New(env, vols.size());
for (uint32_t i = 0; i < vols.size(); i++) {
const VolumeInfo& v = vols[i];
Napi::Object obj = Napi::Object::New(env);
obj.Set("mountpoint", Napi::String::New(env, v.mountpoint));
obj.Set("name", Napi::String::New(env, v.name));
obj.Set("fs", Napi::String::New(env, v.fs));
obj.Set("type", Napi::String::New(env, v.type));
obj.Set("device", Napi::String::New(env, v.device.c_str()));
obj.Set("ok", Napi::Boolean::New(env, v.ok));
if (!v.errMsg.empty()) obj.Set("error", Napi::String::New(env, v.errMsg.c_str()));
if (v.ok) {
obj.Set("usage", big ? BuildResultBig(env, v.usage) : BuildResult(env, v.usage));
} else {
obj.Set("usage", env.Null());
}
arr.Set(i, obj);
}
return arr;
}
Napi::Object BuildDirSizeResult(Napi::Env env, const DirSize& info) {
Napi::Object obj = Napi::Object::New(env);
obj.Set("size", Napi::Number::New(env, static_cast<double>(info.size)));
obj.Set("files", Napi::Number::New(env, static_cast<double>(info.files)));
obj.Set("directories", Napi::Number::New(env, static_cast<double>(info.directories)));
return obj;
}
Napi::Object BuildDirSizeResultBig(Napi::Env env, const DirSize& info) {
Napi::Object obj = Napi::Object::New(env);
obj.Set("size", Napi::BigInt::New(env, info.size));
obj.Set("files", Napi::Number::New(env, static_cast<double>(info.files)));
obj.Set("directories", Napi::Number::New(env, static_cast<double>(info.directories)));
return obj;
}
// ------------------- AsyncWorkers -------------------
class CheckWorker : public Napi::AsyncWorker {
public:
CheckWorker(Napi::Env env, std::string path, bool big)
: Napi::AsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
path_(std::move(path)), big_(big) {}
Napi::Promise GetPromise() { return deferred_.Promise(); }
void Execute() override {
auto err = QueryDisk(path_, info_);
if (!err.empty()) SetError(err);
}
void OnOK() override {
deferred_.Resolve(big_ ? BuildResultBig(Env(), info_) : BuildResult(Env(), info_));
}
void OnError(const Napi::Error& e) override { deferred_.Reject(e.Value()); }
private:
Napi::Promise::Deferred deferred_;
std::string path_;
bool big_;
DiskInfo info_{};
};
class ListWorker : public Napi::AsyncWorker {
public:
ListWorker(Napi::Env env, bool big)
: Napi::AsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)), big_(big) {}
Napi::Promise GetPromise() { return deferred_.Promise(); }
void Execute() override { vols_ = ListVolumes(); }
void OnOK() override { deferred_.Resolve(BuildVolumes(Env(), vols_, big_)); }
void OnError(const Napi::Error& e) override { deferred_.Reject(e.Value()); }
private:
Napi::Promise::Deferred deferred_;
bool big_;
std::vector<VolumeInfo> vols_;
};
class DirSizeWorker : public Napi::AsyncWorker {
public:
DirSizeWorker(Napi::Env env, std::string path, bool big)
: Napi::AsyncWorker(env), deferred_(Napi::Promise::Deferred::New(env)),
path_(std::move(path)), big_(big) {}
Napi::Promise GetPromise() { return deferred_.Promise(); }
void Execute() override {
auto err = QueryDirectorySize(path_, info_);
if (!err.empty()) SetError(err);
}
void OnOK() override {
deferred_.Resolve(big_ ? BuildDirSizeResultBig(Env(), info_) : BuildDirSizeResult(Env(), info_));
}
void OnError(const Napi::Error& e) override { deferred_.Reject(e.Value()); }
private:
Napi::Promise::Deferred deferred_;
std::string path_;
bool big_;
DirSize info_{};
};
// ------------------- Sync exports -------------------
Napi::Value CheckSync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
Napi::TypeError::New(env, "path (string) is required").ThrowAsJavaScriptException();
return env.Undefined();
}
std::string path = info[0].As<Napi::String>().Utf8Value();
DiskInfo di;
auto err = QueryDisk(path, di);
if (!err.empty()) {
Napi::Error::New(env, err).ThrowAsJavaScriptException();
return env.Undefined();
}
return BuildResult(env, di);
}
Napi::Value CheckSyncBig(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
Napi::TypeError::New(env, "path (string) is required").ThrowAsJavaScriptException();
return env.Undefined();
}
std::string path = info[0].As<Napi::String>().Utf8Value();
DiskInfo di;
auto err = QueryDisk(path, di);
if (!err.empty()) {
Napi::Error::New(env, err).ThrowAsJavaScriptException();
return env.Undefined();
}
return BuildResultBig(env, di);
}
Napi::Value CheckAsync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
Napi::TypeError::New(env, "path (string) is required").ThrowAsJavaScriptException();
return env.Undefined();
}
std::string path = info[0].As<Napi::String>().Utf8Value();
auto* worker = new CheckWorker(env, std::move(path), /*big=*/false);
auto p = worker->GetPromise();
worker->Queue();
return p;
}
Napi::Value CheckAsyncBig(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
Napi::TypeError::New(env, "path (string) is required").ThrowAsJavaScriptException();
return env.Undefined();
}
std::string path = info[0].As<Napi::String>().Utf8Value();
auto* worker = new CheckWorker(env, std::move(path), /*big=*/true);
auto p = worker->GetPromise();
worker->Queue();
return p;
}
Napi::Value ListVolumesSync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
auto vols = ListVolumes();
return BuildVolumes(env, vols, /*big=*/false);
}
Napi::Value ListVolumesSyncBig(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
auto vols = ListVolumes();
return BuildVolumes(env, vols, /*big=*/true);
}
Napi::Value ListVolumesAsync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
auto* worker = new ListWorker(env, /*big=*/false);
auto p = worker->GetPromise();
worker->Queue();
return p;
}
Napi::Value ListVolumesAsyncBig(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
auto* worker = new ListWorker(env, /*big=*/true);
auto p = worker->GetPromise();
worker->Queue();
return p;
}
// ---- getDirectorySize ----
Napi::Value GetDirSizeSync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
Napi::TypeError::New(env, "path (string) is required").ThrowAsJavaScriptException();
return env.Undefined();
}
std::string path = info[0].As<Napi::String>().Utf8Value();
DirSize ds;
auto err = QueryDirectorySize(path, ds);
if (!err.empty()) {
Napi::Error::New(env, err).ThrowAsJavaScriptException();
return env.Undefined();
}
return BuildDirSizeResult(env, ds);
}
Napi::Value GetDirSizeSyncBig(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
Napi::TypeError::New(env, "path (string) is required").ThrowAsJavaScriptException();
return env.Undefined();
}
std::string path = info[0].As<Napi::String>().Utf8Value();
DirSize ds;
auto err = QueryDirectorySize(path, ds);
if (!err.empty()) {
Napi::Error::New(env, err).ThrowAsJavaScriptException();
return env.Undefined();
}
return BuildDirSizeResultBig(env, ds);
}
Napi::Value GetDirSizeAsync(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
Napi::TypeError::New(env, "path (string) is required").ThrowAsJavaScriptException();
return env.Undefined();
}
std::string path = info[0].As<Napi::String>().Utf8Value();
auto* worker = new DirSizeWorker(env, std::move(path), /*big=*/false);
auto p = worker->GetPromise();
worker->Queue();
return p;
}
Napi::Value GetDirSizeAsyncBig(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
if (info.Length() < 1 || !info[0].IsString()) {
Napi::TypeError::New(env, "path (string) is required").ThrowAsJavaScriptException();
return env.Undefined();
}
std::string path = info[0].As<Napi::String>().Utf8Value();
auto* worker = new DirSizeWorker(env, std::move(path), /*big=*/true);
auto p = worker->GetPromise();
worker->Queue();
return p;
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set("checkSync", Napi::Function::New(env, CheckSync));
exports.Set("checkAsync", Napi::Function::New(env, CheckAsync));
exports.Set("checkSyncBig", Napi::Function::New(env, CheckSyncBig));
exports.Set("checkAsyncBig", Napi::Function::New(env, CheckAsyncBig));
exports.Set("listVolumesSync", Napi::Function::New(env, ListVolumesSync));
exports.Set("listVolumesSyncBig", Napi::Function::New(env, ListVolumesSyncBig));
exports.Set("listVolumesAsync", Napi::Function::New(env, ListVolumesAsync));
exports.Set("listVolumesAsyncBig",Napi::Function::New(env, ListVolumesAsyncBig));
exports.Set("getDirectorySizeSync", Napi::Function::New(env, GetDirSizeSync));
exports.Set("getDirectorySizeSyncBig", Napi::Function::New(env, GetDirSizeSyncBig));
exports.Set("getDirectorySizeAsync", Napi::Function::New(env, GetDirSizeAsync));
exports.Set("getDirectorySizeAsyncBig",Napi::Function::New(env, GetDirSizeAsyncBig));
return exports;
}
} // namespace
NODE_API_MODULE(diskusage, Init)