1. 程式人生 > >node.js刪除資料夾及檔案

node.js刪除資料夾及檔案

node.js的fs模組只提供了刪除檔案unlink夾及目錄rmdir的功能,所以一起刪除需要我們遍歷刪除,程式碼如下

var fs = require('fs'); // 引入fs模組

function deleteall(path) {
	var files = [];
	if(fs.existsSync(path)) {
		files = fs.readdirSync(path);
		files.forEach(function(file, index) {
			var curPath = path + "/" + file;
			if(fs.statSync(curPath).isDirectory()) { // recurse
				deleteall(curPath);
			} else { // delete file
				fs.unlinkSync(curPath);
			}
		});
		fs.rmdirSync(path);
	}
};

使用
deleteall("./dir")//將資料夾傳入即可