fswin32
Version:
The ultimate Node.js module for detailed Windows file system access.
37 lines (32 loc) • 1.25 kB
JavaScript
// src/utils.js
import { exec } from 'child_process';
import util from 'util';
const execPromise = util.promisify(exec);
/**
* Converts bytes to a human-readable format (e.g., KB, MB, GB).
* @param {number} bytes The size in bytes.
* @param {number} decimals The number of decimal places.
* @returns {string} The formatted size string.
*/
export const formatBytes = (bytes, decimals = 2) => {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
};
/**
* Executes a PowerShell command and returns the output.
* @param {string} command The PowerShell command to execute.
* @returns {Promise<string|null>} The stdout of the command or null on error.
*/
export const executePowerShellCommand = async (command) => {
try {
const { stdout } = await execPromise(`powershell -ExecutionPolicy Bypass -Command "${command}"`);
return stdout;
} catch (error) {
// console.error('PowerShell command failed:', error.message);
return null;
}
};