Home  >  Article  >  Web Front-end  >  NodeJS traverse files to produce file list function example

NodeJS traverse files to produce file list function example

高洛峰
高洛峰Original
2017-02-04 10:43:491179browse

The example in this article describes the function of NodeJS traversing files to produce a file list. Share it with everyone for your reference, the details are as follows:

Functional requirements: At work, we may often need to know the list of static files in the project to be published, and it would be too hard to retrieve and write them one by one.

NodeJS traverse files to produce file list function example

# If you want to know the file list inside, is it painful? Maybe we will also have dos tree to get it.

Share here, know the file path through node, configure the remote path, copy and publish directly.

There are comments in the new filelist.js, so I won’t shiver.

var fs = require("fs");
//path模块,可以生产相对和绝对路径
var path = require("path");
//配置远程路径
var remotePath = "/resource/fd/promote/201507/qixi/";
//获取当前目录绝对路径,这里resolve()不传入参数
var filePath = path.resolve();
//读取文件存储数组
var fileArr = [];
//读取文件目录
fs.readdir(filePath,function(err,files){
  if(err){
    console.log(err);
    return;
  }
  var count = files.length;
  //console.log(files);
  var results = {};
  files.forEach(function(filename){
    //filePath+"/"+filename不能用/直接连接,Unix系统是”/“,Windows系统是”\“
    fs.stat(path.join(filePath,filename),function(err, stats){
      if (err) throw err;
      //文件
      if(stats.isFile()){
        if(getdir(filename) == 'html'){
          var newUrl=remotePath+filename;
          fileArr.push(newUrl);
          writeFile(fileArr);
        }
        // (getdir(filename) == 'html')&&(fileArr.push(filename);writeFile(newUrl));
      //  console.log("%s is file", filename);
      }else if(stats.isDirectory()){
        // console.log("%s is a directory文件目录", filename);
         //返回指定文件名的扩展名称 
         //console.log(path.extname("pp/index.html"));
         if(filename == 'css' || filename == 'images'){
//var readurl = filePath+'/'+filename;
             //filePath+"/"+filename不能用/直接连接,Unix系统是”/“,Windows系统是”\“
           //  console.log(path.join(filePath,filename));
             var name = filename;
             readFile(path.join(filePath,filename),name);
         }
      }
    });
  });
});
//获取后缀名
function getdir(url){
  var arr = url.split('.');
  var len = arr.length;
  return arr[len-1];
}
//获取文件数组
function readFile(readurl,name){
  console.log(name);
  var name = name;
  fs.readdir(readurl,function(err,files){
    if(err){console.log(err);return;}
    files.forEach(function(filename){
     // console.log(path.join(readurl,filename));
      fs.stat(path.join(readurl,filename),function(err, stats){
        if (err) throw err;
        //是文件
        if(stats.isFile()){
          var newUrl=remotePath+name+'/'+filename;
          fileArr.push(newUrl);
          writeFile(fileArr)
        //是子目录
        }else if(stats.isDirectory()){
          var dirName = filename;
          readFile(path.join(readurl,filename),name+'/'+dirName);
          //利用arguments.callee(path.join())这种形式利用自身函数,会报错
          //arguments.callee(path.join(readurl,filename),name+'/'+dirName);
        }
      });
    });
  });
}
// 写入到filelisttxt文件
function writeFile(data){
  var data = data.join("\n");
  fs.writeFile(filePath+"/"+"filelist.txt",data+'\n',function(err){
    if(err) throw err;
    console.log("写入成功");
  });
}

When we execute

node flielist.js

, filelist.txt will be produced , the file contains the path we want.

NodeJS traverse files to produce file list function example

Sometimes, we usually encounter files that cannot be deleted. Because the file depth is too long, rm _rf cannot be deleted, but we can do it through nodejs:

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("./grunt");

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

For more NodeJS file traversal file production file list function 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
Previous article:nodejs basic knowledgeNext article:nodejs basic knowledge