有没有办法使用 node.js 查找服务器端硬盘驱动器名称,如 C:、D:、E: 等?
In windows, you can use this command wmic logicaldisk get caption
.
In Nodejs, you can spawn a new process to this cammand.
var exec = require('child_process').exec;
function showLetter(callback) {
exec('wmic logicaldisk get caption', function(err, stdout, stderr) {
if(err || stderr) {
console.log("root path open failed" + err + stderr);
return;
}
callback(stdout);
}
}
We built a module called drivelist do to exactly this, and works in all major operating systems. In Windows, for example, you might get an output similar to this one:
[
{
device: '\\\\.\\PHYSICALDRIVE0',
description: 'WDC WD10JPVX-75JC3T0',
size: '1000 GB'
mountpoint: 'C:',
system: true
},
{
device: '\\\\.\\PHYSICALDRIVE1',
description: 'Generic STORAGE DEVICE USB Device',
size: '15 GB'
mountpoint: 'D:',
system: false
}
]
Notice it lists both removable and non-removable drives, although you can distinguish between them by the system
property.
Node.js way:
import * as path from 'path';
const cwdOSRoot = path.parse(process.cwd()).root;
const fileOSRoot = path.parse(__dirname).root;
Important to note, one will get you the letter of the current working directory , the other the drive letter of the drive where the file containing this code is on . You can replace process.cwd()
and __dirname
with any absolute path to get the drive letter.
Second way:
import * as os from 'os';
import * as path from 'path';
const cwdOSRoot = os.platform() === 'win32' ? `${process.cwd().split(path.sep)[0]}:` : '/';
const fileOSRoot = os.platform() === 'win32' ? `${__dirname.split(path.sep)[0]}:` : '/';
Then just use path.join
, path.normalize
, path.resolve
etc.. This code will work for any OS.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.