xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

Node.js delete directory & file system All In One

Node.js delete directory & file system All In One

delete a not empty directory

https://nodejs.org/api/fs.htm

fs.rmdir(path[, options], callback)
fs.rmdirSync(path[, options])

recursive: true

In a Node.js application, you can use the fs.rmdir() method to delete a directory.

This method works asynchronously to remove the directory.

If the directory is not empty, you can pass an optional recursive flag to delete all nested files and folders recursively.

const fs = require('fs');

// directory path
const dir = 'temp';

// delete directory recursively
fs.rmdir(dir, { recursive: true }, (err) => {
    if (err) {
        throw err;
    }

    console.log(`${dir} is deleted!`);
});

const fs = require('fs');

// directory path
const dir = 'temp';

// delete directory recursively
try {
    fs.rmdirSync(dir, { recursive: true });

    console.log(`${dir} is deleted!`);
} catch (err) {
    console.error(`Error while deleting ${dir}.`);
}

del

https://www.npmjs.com/package/del

$ npm i -D del

https://github.com/sindresorhus/del/blob/master/index.js

trash

https://github.com/sindresorhus/trash/blob/master/index.js

rimraf

https://www.npmjs.com/package/rimraf

$ npm i -D rimraf

https://github.com/isaacs/rimraf/blob/master/rimraf.js

refs

https://attacomsian.com/blog/nodejs-delete-directory

https://geedew.com/remove-a-directory-that-is-not-empty-in-nodejs/


var fs = require('fs');
var deleteFolderRecursive = function(path) {
  if( fs.existsSync(path) ) {
    fs.readdirSync(path).forEach(function(file,index){
      var curPath = path + "/" + file;
      if(fs.lstatSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);
      } else { // delete file
        fs.unlinkSync(curPath);
      }
    });
    fs.rmdirSync(path);
  }
};

unlink

https://stackoverflow.com/questions/39963966/can-fs-unlink-delete-a-empty-or-non-empty-folder

https://stackoverflow.com/questions/18052762/remove-directory-which-is-not-empty/32197381



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @   xgqfrms  阅读(324)  评论(4编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2019-07-09 c9.io & aws cloud9
2019-07-09 git server
2019-07-09 微信分享
2019-07-09 js & input event & input change event
2016-07-09 Virtual Studio Code 1.3.0 vs Sublime Text 3114 使用感受 All In One
2016-07-09 Docker Overview All In One
点击右上角即可分享
微信分享提示