適用場景: 當一個文件夾中需要在多個地方刪除某個文件夾或者文件時,鼠標操作較為繁瑣. 這時可以通過nodejs的文件系統進行操作.
正文:於是在參考某個網友代碼基礎上進行修改,實現批量刪除一個文件夾中的某個文件夾或文件.廢話不多說,直接上代碼:
---------------------------------------------------------------------------------------------------
let fs = require('fs'); // 引入fs模塊
function deleteall(path) {
let files = [];
if(fs.existsSync(path)) {
files = fs.readdirSync(path);
files.forEach(function (file, index) {
// console.log(file);
let curPath = path + "/" + file;
console.log(curPath);
if(fs.statSync(curPath).isDirectory()) { // recurse
deleteall(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
}
};
function findFile(path, findName) {
let filesAll = [];
if (fs.existsSync(path)) {
filesAll = fs.readdirSync(path);
filesAll.forEach((fileItem,index) => {
let findCurrPath = path + '/' + fileItem;
if (fileItem == findName) {
console.log(findCurrPath);
deleteall(findCurrPath);
findFile(path,findName);
} else {
if(fs.statSync(findCurrPath).isDirectory()) { // recurse
findFile(findCurrPath,findName);
}
}
})
}
}
findFile('文件夾絕對路徑','文件名或文件夾名')
----------------------------------------------------------------------------------------------
如何使用:
1.第一步: 創建一個js文件,將代碼copy進去
2.第二步: 在該js文件目錄下,打開 CMD 窗口
// 運行前需要將文件夾路徑需要更改
3.第三步: 輸入 '' node js文件名 '' 然后回車
4.第四步: 運行成功,刪除文件成功
好了!
到此文件刪除成功,如有幫助麻煩點個贊,謝謝!!!