C盘空间释放node脚本
•25 字•1 分钟阅读
工具
注意:谨慎使用!!需要使用管理员身份运行脚本
代码:
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
const os = require('os');
const username = os.userInfo().username;
const targets = [
// 1. Windows 系统临时文件
`C:\\Windows\\Temp`,
// 2. 当前用户的临时文件
`C:\\Users\\${username}\\AppData\\Local\\Temp`,
// 3. 浏览器缓存
`C:\\Users\\${username}\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Cache`,
`C:\\Users\\${username}\\AppData\\Local\\Microsoft\\Edge\\User Data\\Default\\Code Cache`,
// 4. Node.js 相关缓存 (npm 和 npx 缓存)
`C:\\Users\\${username}\\AppData\\Local\\npm-cache`,
// 5. 预读取文件
`C:\\Windows\\Prefetch`
];
// 优化的递归删除函数
function deleteFolderRecursive(dirPath) {
if (!fs.existsSync(dirPath)) return;
try {
const files = fs.readdirSync(dirPath);
for (const file of files) {
const curPath = path.join(dirPath, file);
try {
const stats = fs.lstatSync(curPath);
if (stats.isDirectory()) {
deleteFolderRecursive(curPath);
} else {
fs.unlinkSync(curPath);
}
} catch (err) {
// 遇到权限不足或文件被占用,直接跳过该文件/文件夹
if (err.code === 'EPERM' || err.code === 'EBUSY') {
console.log(`⚠️ 跳过被占用或无权限的文件: ${curPath}`);
continue;
}
throw err;
}
}
// 尝试删除当前空文件夹
fs.rmdirSync(dirPath);
console.log(`✅ 成功清理文件夹: ${dirPath}`);
} catch (err) {
// 如果整个文件夹都无法读取(如 vmware-SYSTEM),直接跳过
if (err.code === 'EPERM' || err.code === 'EBUSY') {
console.log(`⚠️ 跳过受保护或无法访问的文件夹: ${dirPath}`);
} else {
console.log(`❌ 清理失败: ${dirPath} - ${err.message}`);
}
}
}
console.log('🚀 开始深度清理 C 盘垃圾文件...\n');
targets.forEach(target => {
deleteFolderRecursive(target);
});
console.log('\n🧹 正在执行 npm cache clean --force...');
exec('npm cache clean --force', (error, stdout, stderr) => {
if (error) {
console.log(`npm 缓存清理提示: ${error.message}`);
return;
}
console.log('✅ npm 缓存清理完成!\n');
console.log('🎉 C 盘清理任务全部结束!');
});