如何使用javascript删除本地文件夹

时间:2022-10-12 23:54:44

I want to delete an empty/non-empty directory from my local system and i have restriction that i need to do that only using javascript functions.I cannot refer to functions like 'FileSystemObject' Please help!

我想从我的本地系统中删除一个空/非空目录,我有限制,我只需要使用javascript函数。我不能引用像'FileSystemObject'这样的函数请帮忙!

Please Note: I need solution for above issue as I am working on mobile app which support javascript only

请注意:我需要上述问题的解决方案,因为我正在开发仅支持javascript的移动应用程序

1 个解决方案

#1


0  

This function should work. Removes files synchronously Pass removeself = true to remove the empty directory.

这个功能应该有效。同步删除文件传递removeself = true删除空目录。

 const path = require('path');
 const fs = require('fs');
 const rmDir = function (dirPath, removeSelf) {
  if (removeSelf === undefined)
    removeSelf = true;
  try {
    var files = fs.readdirSync(dirPath);
  } catch (e) {
    // throw e
    return;
  }
  if (files.length > 0)
    for (let i = 0; i < files.length; i++) {
      const filePath = path.join(dirPath, files[i]);
      if (fs.statSync(filePath).isFile())
        fs.unlinkSync(filePath);
      else
        rmDir(filePath);
    }
  if (removeSelf)
    fs.rmdirSync(dirPath);
};

Disclaimer: Not my code, copied from someone's gist(forgot the url).

免责声明:不是我的代码,从某人的要点复制(忘记了网址)。

#1


0  

This function should work. Removes files synchronously Pass removeself = true to remove the empty directory.

这个功能应该有效。同步删除文件传递removeself = true删除空目录。

 const path = require('path');
 const fs = require('fs');
 const rmDir = function (dirPath, removeSelf) {
  if (removeSelf === undefined)
    removeSelf = true;
  try {
    var files = fs.readdirSync(dirPath);
  } catch (e) {
    // throw e
    return;
  }
  if (files.length > 0)
    for (let i = 0; i < files.length; i++) {
      const filePath = path.join(dirPath, files[i]);
      if (fs.statSync(filePath).isFile())
        fs.unlinkSync(filePath);
      else
        rmDir(filePath);
    }
  if (removeSelf)
    fs.rmdirSync(dirPath);
};

Disclaimer: Not my code, copied from someone's gist(forgot the url).

免责声明:不是我的代码,从某人的要点复制(忘记了网址)。