Home > Article > Web Front-end > How to delete a folder in nodejs
Nodejs method to delete a folder: 1. Create a js sample file; 2. Introduce the fs module; 3. Delete the folder through the "function deleteall(path) {...}" method.
The operating environment of this article: Windows 7 system, nodejs version 10.16.2, DELL G3 computer
#How to delete a folder in nodejs?
node.js Delete folders and files:
The fs module of node.js only provides the function of deleting the file unlink folder and directory rmdir, so delete them together. We need to traverse and delete, the code is as follows
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); } };
Use
deleteall("./dir")//将文件夹传入即可
Update:
Haha, I found a more convenient code to use nodejs to call system commands Ability to use system commands to delete. I used to use npm run xxx in xxx to delete. However, due to compatibility issues with different commands in the system, I have to come to nodejs to judge the system
var exec = require('child_process').exec; var cmdStr = 'rm -rf xxhbg_app_src/webapp'; exec(cmdStr, function (err, stdout, srderr) { if (err) { console.log(srderr); } else { console.log(stdout); } });
Recommended learning: "node.js Video Tutorial"
The above is the detailed content of How to delete a folder in nodejs. For more information, please follow other related articles on the PHP Chinese website!