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

NodeJS traverse files to produce file list function example

高洛峰
Release: 2017-02-04 10:43:49
Original
1251 people have browsed it

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

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("写入成功");

  });

}

Copy after login

When we execute

1

node flielist.js

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

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");

Copy after login

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!

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