使用JavaScript/nodejs计算目录中的文件数量?

w8ntj3qf  于 2023-06-05  发布在  Node.js
关注(0)|答案(8)|浏览(677)

如何使用nodejs计算目录中的文件数,而只使用普通的JavaScript或包?我想做这样的事情:
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
}
fcwjkofz

fcwjkofz1#

使用fs,我发现检索目录文件数非常简单。

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

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

对于TS爱好者:

fs.readdir(dir, (err: NodeJS.ErrnoException | null, files: string[]) => {
  console.log(files.length);
});
iswrvxsc

iswrvxsc2#

const fs = require('fs')
const length = fs.readdirSync('/home/directory').length
amrnrhlw

amrnrhlw3#

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文件夹(countFiles.js所在的文件夹)中打开命令promt,并写入node countFiles "DESTINATION_FOLDER"(例如:node countFiles "C:\Users\MyUser\Desktop\testFolder"

nxowjjhe

nxowjjhe4#

没有外部模块的替代解决方案,可能不是最有效的代码,但将在没有外部依赖的情况下完成任务:

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);
});
vwoqyblh

vwoqyblh5#

这里的简单代码,

import RNFS from 'react-native-fs';
RNFS.readDir(dirPath)
    .then((result) => {
     console.log(result.length);
});
gblwokeq

gblwokeq6#

好的,我有一个类似bash脚本的方法:

const shell = require('shelljs')
const path = require('path')

module.exports.count = () => shell.exec(`cd ${path.join('path', 'to', 'folder')} || exit; ls -d -- */ | grep 'page-*' | wc -l`, { silent:true }).output

就这样

euoag5mw

euoag5mw7#

const readdir = (path) => {
  return new Promise((resolve, reject) => {
    fs.readdir(path, (error, files) => {
      error ? reject(error) : resolve(files);
    });
  });
};s

readdir("---path to directory---").then((files) => {
  console.log(files.length);
});
bxfogqkk

bxfogqkk8#

我想很多人都在寻找这样的函数:

const countFiles = (dir: string): number =>
  fs.readdirSync(dir).reduce((acc: number, file: string) => {
    const fileDir = `${dir}/${file}`;

    if (fs.lstatSync(fileDir).isDirectory()) {
      return (acc += countFiles(fileDir));
    }

    if (fs.lstatSync(fileDir).isFile()) {
      return ++acc;
    }

    return acc;
  }, 0);

它们计算整个文件树中的所有文件。

相关问题