我可以帮您翻译中文。需要翻译的内容与IT技术相关,您希望计算并显示主文件系统的可用空间,但有3-4个用户,并且所有用户都应该在JavaScript中操作。我们该怎么做呢?
我知道在Linux Shell中,我们可以执行以下操作:
我知道在Linux Shell中,我们可以执行以下操作:
df -h
但是在javascript中不是这样的
df -h
但是在javascript中不是这样的
Node diskusage将会实现此功能。有关该软件包的更多信息,请参阅diskusage文档:
import { check } from "diskusage";
const log = console.log.bind(console);
async function getFreeSpace(path) {
const diskUsage = await check(path);
log(`Disk space available to the current user: ${diskUsage.free}`);
log(`Disk space physically free: ${diskUsage.free}`);
log(`Total disk space (free + used): ${diskUsage.free}`);
}
getFreeSpace("/home/mike");
NodeJS在v19.6中增加了对statfs
和statfsSync
的支持。
import { statfs } from 'fs';
// path in mounted volume
const pathToCheck = '/';
const space = statfs(pathToCheck, (err, stats) => {
if (err) {
throw err
}
console.log('Total free space',stats.bsize*stats.bfree);
console.log('Available for user',stats.bsize*stats.bavail);
})
不要嫌我太自夸 - https://www.npmjs.com/package/microstats
还可以配置,当磁盘空间超过用户定义的阈值时通知用户。适用于Linux、macOS和Windows。
var spawn = require('child_process').spawn;
var df = spawn('df', ['-h']);
df.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
df.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
df.on('close', function (code) {
console.log('子进程退出代码:' + code);
});
你之前用过NodeJS吗?你知道如何设置它吗? - NMunro你可以使用diskusage npm和child_process.exec('df / -h')来获取这个参数。 但是diskusage npm更可靠且易于使用。如果你使用cp.exec('...'),你需要自己处理返回的字符串以获取所需的参数。
df -h > df.txt
来将 df -h
的输出写入名为 df.txt
的文件中。然后你可以读取该文件并匹配一个正则表达式。const { execSync } = require('child_process');
const { readFileSync, unlinkSync } = require('fs')
var space;
execSync('df -h > df.txt');
space = readFileSync('df.txt', (data, err) => {
if (err) {
throw err
}
}).toString().match(/[0-9]+\.[0-9]+?../)[0]
console.log(space)
execSync
而不是exec
。 - deebugger