2013-10-08 37 views
1

我有一個文件夾的絕對路徑。是否有任何方法知道它包含的子文件夾的數量並獲取所有子文件夾的名稱JavaScript(nodejs)。 我GOOGLE了它,但找不到任何解決方案。如何知道所有子文件夾的名稱

+0

你需要一個服務器端語言來做到這一點,如PHP。但你可以使用ajax調用一個返回列表的php腳本,然後用JavaScript處理它 – rorypicko

+0

我正在嘗試使用Nodejs。是否有可能使用Nodejs – pnkz

+0

好吧,我不確定,今後請提及您正在使用的技術。 – rorypicko

回答

1

你想要the fs module

var fs = require('fs'); 
var path = '/Users/quentin'; 
var filenames = fs.readdirSync(path); 
var count = 0; 
filenames.forEach(function (name) { 
    if (name === "." || name === "..") { 
     return; 
    } 
    if (fs.lstatSync(path + "/" + name).isDirectory()) { 
     count++; 
    } 

}); 
console.log(count); 
0

您可以使用這樣的事情:

var fs = require('fs'); 
var path = require('path'); 

var uid = process.getuid(); 
var gid = process.getgid(); 

function countDirs(dir, depth) { 
    if (! depth) return 0; 
    depth--; 

    var dirs = fs.readdirSync(dir); 
    var result = 0; 
    var item, stat; 
    while(dirs.length) { 
     item = path.join(dir, dirs.shift()); 
     stat = fs.lstatSync(item); 

     if (! stat.isDirectory()) continue; 
     var mode = stat.mode.toString(8).split(); 
     result++; 
     // If process allowed to read dir 
     if (stat.uid === uid || stat.guid === gid && mode[3] > 3 || mode[4] > 3) { 
      result += countDirs(item, depth); 
     } 
    } 
    return result; 
} 
// Example usage 
var count = countDirs(process.cwd(), 1); 
console.log('Total dirs count:', count); 

注意!不要忘記權限!

相關問題