Last active
February 23, 2019 14:00
-
-
Save hawkeye64/66ea8b0f258c7869f4845474870b5005 to your computer and use it in GitHub Desktop.
A function that returns in a callback (error, results) an array of Windows drives in use ['C:', 'D:'] etc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const exec = require('child_process').exec | |
const fs = require('fs') | |
const path = require('path') | |
function getWindowsDrives (callback) { | |
if (!callback) { | |
throw new Error('getWindowsDrives called with no callback') | |
} | |
if (process.platform !== 'win32') { | |
throw new Error('getWindowsDrives called but process.plaform !== \'win32\'') | |
} | |
let drives = [] | |
exec('wmic LOGICALDISK LIST BRIEF', (error, stdout) => { | |
if (error) { | |
callback(error, drives) | |
return | |
} | |
// get the drives | |
let parts = stdout.split('\n') | |
if (parts.length) { | |
// first part is titles; get rid of it | |
parts.splice(0, 1) | |
for (let index = 0; index < parts.length; ++index) { | |
let drive = parts[index].slice(0, 2) | |
if (drive.length && drive[drive.length - 1] === ':') { | |
try { | |
// if stat fails, it'll throw an exception | |
fs.statSync(drive + path.sep) | |
drives.push(drive) | |
} | |
catch (e) { | |
console.error(`Cannot stat windows drive: ${drive}`, e) | |
} | |
} | |
} | |
callback(null, drives) | |
} | |
}) | |
} | |
export default getWindowsDrives |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
done, Thanks!