简体   繁体   English

我可以使用 node.js 找到服务器端硬盘驱动器号吗?

[英]Can I find server-side hard drive letter using node.js?

有没有办法使用 node.js 查找服务器端硬盘驱动器名称,如 C:、D:、E: 等?

In windows, you can use this command wmic logicaldisk get caption .在 Windows 中,您可以使用此命令wmic logicaldisk get caption

In Nodejs, you can spawn a new process to this cammand.在 Nodejs 中,您可以为该命令生成一个新进程。

 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.我们为此构建了一个名为drivelist do 的模块,并且可以在所有主要操作系统中使用。 In Windows, for example, you might get an output similar to this one:例如,在 Windows 中,您可能会得到与此类似的输出:

[
    {
        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.请注意,它列出了可移动和不可移动驱动器,但您可以通过system属性来区分它们。

Node.js way: Node.js 方式:

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.您可以使用任何绝对路径替换process.cwd()__dirname以获取驱动器号。

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.然后只需使用path.joinpath.normalizepath.resolve等。此代码适用于任何操作系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM