Count the number of files in a directory using JavaScript/nodejs?
我如何计算一个目录中使用
如何使用python计算目录中的文件数
或者在bash脚本中,我会这样做:
1 2 3 4 5 6 | getLength() { DIRLENGTH=1 until [ ! -d"DIR-$((DIRLENGTH+1))" ]; do DIRLENGTH=$((DIRLENGTH+1)) done } |
利用
1 2 3 4 5 6 | const fs = require('fs'); const dir = './directory'; fs.readdir(dir, (err, files) => { console.log(files.length); }); |
没有外部模块的替代方案,也许不是最高效的代码,但是这会做的伎俩:没有外部依赖
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 | 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); }); |
1)和下载shell.js Node.js(如果你不想要它) 2)去下载它,你有一个文件的创建和命名
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 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冰)和写(如
在这里,简单的代码
1 2 3 4 5 | import RNFS from 'react-native-fs'; RNFS.readDir(dirPath) .then((result) => { console.log(result.length); }); |
好的,我有一个简单的方法是:
1 2 3 4 5 6 7 | 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; |
好的信息。