1 回答
TA貢獻1802條經驗 獲得超6個贊
您可以使用 fs.readdirSync 列出文件,然后調用 fs.unlinkSync 進行刪除。這可以遞歸調用以遍歷整個樹。
const fs = require("fs");
const path = require("path");
function deleteRecursively(dir, pattern) {
let files = fs.readdirSync(dir).map(file => path.join(dir, file));
for(let file of files) {
const stat = fs.statSync(file);
if (stat.isDirectory()) {
deleteRecursively(file, pattern);
} else {
if (pattern.test(file)) {
console.log(`Deleting file: ${file}...`);
// Uncomment the next line once you're happy with the files being logged!
try {
//fs.unlinkSync(file);
} catch (err) {
console.error(`An error occurred deleting file ${file}: ${err.message}`);
}
}
}
}
}
deleteRecursively('./some_dir', /\.json$/);
我實際上已經將刪除文件的行注釋掉了.. 我建議你運行腳本并且很高興記錄的文件是正確的。然后只需取消注釋 fs.unlinkSync 行即可刪除文件。
添加回答
舉報
