nodejs 遍歷文件夾 獲取 文件夾下所有文件列表


一直關注node.js的發展,但是沒有動手寫過東西,前面同事幫忙用python寫了個工具,

獲取一個文件夾下面的所有文件名的列表,python真的是強大,俺決定用node來寫一個。

使用方法,把下面代碼保存為一個js文件比如xxoo.js ,然后打開命令行工具,進入xxoo.js

所在目錄,輸入:

node xxoo.js '這里為你要統計的目標文件夾的目錄'

然后 你會 在 xxoo.js所在目錄,發現一個res.lst的文件名,這個文件名 由你自己決定,見

代碼第三行,這個文件里面就包含了你要統計目錄的所有子文件列表。

 1 var fs = require('fs');
2 var root_path=process.argv[2];
3 var w_file='res.lst';
4 function getAllFiles(root){
5 var res = [] , files = fs.readdirSync(root);
6 files.forEach(function(file){
7 var pathname = root+'/'+file
8 , stat = fs.lstatSync(pathname);
9
10 if (!stat.isDirectory()){
11 res.push(pathname.replace(root_path,'.'));
12 } else {
13 res = res.concat(getAllFiles(pathname));
14 }
15 });
16 return res
17 }
18 var w_content=getAllFiles(root_path).join('\n');
19 fs.readFile(root_path+w_file,function(err , data){
20 if(err && err.errno==33){
21 fs.open(w_file,"w",0666,function(e,fd){
22 if(e) throw e;
23 fs.write(fd,w_content,0,'utf8',function(e){
24 if(e) throw e;
25 fs.closeSync(fd);
26 })
27 });
28 } else{
29 fs.writeFile(root_path+w_file,w_content,function(e){
30 if(e) throw e
31 })
32 }
33 })


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM