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

NodeJS traverse files to produce file list function example

Feb 04, 2017 am 10:43 AM

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

When we execute

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:

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles