Home > Web Front-end > JS Tutorial > body text

How to delete a folder in nodejs

藏色散人
Release: 2021-10-28 15:04:54
Original
6774 people have browsed it

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.

How to delete a folder in nodejs

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);
}
};
Copy after login

Use

deleteall("./dir")//将文件夹传入即可
Copy after login

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);
  }
});
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template