2015-11-18 79 views
4

如何使用nodejs僅使用普通的JavaScript或包來計算目錄中的文件數量?我想要做這樣的事情:使用JavaScript/nodejs計算目錄中的文件數量?

How to count the number of files in a directory using Python

或者在bash腳本我應該這樣做:

getLength() { 
    DIRLENGTH=1 
    until [ ! -d "DIR-$((DIRLENGTH+1))" ]; do 
    DIRLENGTH=$((DIRLENGTH+1)) 
    done 
} 
+1

你到目前爲止嘗試過什麼? – Ziki

+0

這絕對有可能。你有關於它的特殊問題嗎? –

+4

[在node.js中獲取目錄中的所有文件名]的可能重複(http://stackoverflow.com/questions/2727167/getting-all-filenames-in-a-directory-with-node-js) –

回答

14

使用fs,我發現檢索目錄文件數量很簡單。

const fs = require('fs'); 
const dir = './directory'; 

fs.readdir(dir, (err, files) => { 
    console.log(files.length); 
}); 
+0

這對我不起作用 – creator

+1

@creator你在控制檯看到什麼錯誤? –

+0

我已經實現了上面的,它顯示上面的語法是錯誤的。我已經將=>替換爲function()。在上面執行之後,我遇到了未定義的「files.length」 – creator

2

1)下載shell.js和node.js的(如果你不這樣做擁有它)
2)去你下載它,並創建有一個文件名爲countFiles.js

var sh = require('shelljs'); 

var count = 0; 
function annotateFolder (folderPath) { 
    sh.cd(folderPath); 
    var files = sh.ls() || []; 

    for (var i=0; i<files.length; i++) { 
    var file = files[i]; 

    if (!file.match(/.*\..*/)) { 
     annotateFolder(file); 
     sh.cd('../'); 
    } else { 
     count++; 
    } 
    } 
} 
if (process.argv.slice(2)[0]) 
    annotateFolder(process.argv.slice(2)[0]); 
else { 
    console.log('There is no folder'); 
} 

console.log(count); 

3)打開shelljs文件夾中的命令promt(其中countFiles.js是)並寫入node countFiles "DESTINATION_FOLDER"(例如, node countFiles "C:\Users\MyUser\Desktop\testFolder"

2

無需外部模塊替代解決方案,也許不是最有效的代碼,但會做的伎倆沒有外部的依賴:

var fs = require('fs'); 

function sortDirectory(path, files, callback, i, dir) { 
    if (!i) {i = 0;}           //Init 
    if (!dir) {dir = [];} 
    if(i < files.length) {          //For all files 
     fs.lstat(path + '\\' + files[i], function (err, stat) { //Get stats of the file 
      if(err) { 
       console.log(err); 
      } 
      if(stat.isDirectory()) {       //Check if directory 
       dir.push(files[i]);        //If so, ad it to the list 
      } 
      sortDirectory(callback, i + 1, dir);    //Iterate 
     }); 
    } else { 
     callback(dir);           //Once all files have been tested, return 
    } 
} 

function listDirectory(path, callback) { 
    fs.readdir(path, function (err, files) {     //List all files in the target directory 
     if(err) { 
      callback(err);          //Abort if error 
     } else { 
      sortDirectory(path, files, function (dir) {   //Get only directory 
       callback(dir); 
      }); 
     } 
    }) 
} 

listDirectory('C:\\My\\Test\\Directory', function (dir) { 
    console.log('There is ' + dir.length + ' directories: ' + dir); 
}); 
0

好,我明白了這個簡單的方法:

function count() { 
    var shell = require('shelljs'); 

    return shell.exec("cd destinationFolder || exit; ls -d -- */ | grep 'page-*' | wc -l", { silent:true }).output; 
} 

module.exports.count = count; 

就是這樣。

相關問題