Home >Web Front-end >JS Tutorial >nodeJS delete file method example

nodeJS delete file method example

高洛峰
高洛峰Original
2017-02-04 10:56:011584browse

The example in this article describes the nodeJS method of deleting files. Share it with everyone for your reference, the details are as follows:

var fs = require("fs");
var path = require("path");
deleteFolderRecursive = function(url) {
  var files = [];
  //判断给定的路径是否存在
  if( fs.existsSync(url) ) {
    //返回文件和子目录的数组
    files = fs.readdirSync(url);
    files.forEach(function(file,index){
      // var curPath = url + "/" + file;
      var curPath = path.join(url,file);
      //fs.statSync同步读取文件夹文件,如果是文件夹,在重复触发函数
      if(fs.statSync(curPath).isDirectory()) { // recurse
        deleteFolderRecursive(curPath);
      // 是文件delete file
      } else {
        fs.unlinkSync(curPath);
      }
    });
    //清除文件夹
    fs.rmdirSync(url);
  }else{
    console.log("给定的路径不存在,请给出正确的路径");
  }
};
deleteFolderRecursive("./node_modules");

I hope this article will be helpful to everyone in nodejs programming.

For more nodeJS file deletion method examples and related articles, please pay attention to the PHP Chinese website!

Statement:
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