文件数未正确计数 [英] Files number not counting properly
问题描述
我有一个包含 264420 个文件的目录
I have a directory with 264420 files
$ find /Users/Username -type f | wc -l
264420
我正在尝试使用简单的counter++
I'm trying to count the file number recursively in Node.js with simple counter++
问题在于counter++
提供的文件数量不正确,而array.push(file)
最后带有array.length
的文件可以正常工作,并提供正确数量的文件- 264420
The issue is that counter++
gives incorrect number of files, while array.push(file)
with array.length
in the end working just fine and gives back correct amount of files - 264420
$ node total-files.js
114 'total_files_count'
264420 'total_files_array_count'
简化的脚本如下所示:
const fs = require('fs')
const path = require('path')
const dir = '/Users/Username'
let totalFiles = 0
let totalFilesArray = []
const totalFilesObj = getFilesRecursively(dir, totalFiles, totalFilesArray)
console.log(totalFilesObj.total_files, 'total_files_count', totalFilesObj.total_files_array.length, 'total_files_array_count')
function getFilesRecursively(dir, totalFiles, totalFilesArray){
totalFiles = totalFiles || 0
totalFilesArray = totalFilesArray || []
try { var files = fs.readdirSync(dir) }
catch(err) { console.error(err.message) }
for (var i in files) {
var name = path.join(dir, files[i])
try {
let stats = fs.lstatSync(name) // track symlink as link, but not as file
if (stats.isDirectory())
getFilesRecursively(name, totalFiles, totalFilesArray)
else if (stats.isFile()) {
totalFiles++ // why this not working? so we should use .push to array instead?
totalFilesArray.push(name)
}
} catch(err) { console.error(err.message) }
}
return { "total_files" : totalFiles, "total_files_array" : totalFilesArray }
}
我正计划在具有成千上万个文件的大型目录上运行脚本,并希望使用比推入数组要快的计数器增量.
I'm planning to run the script on large directories with hundreds of thousands of files and want to use counter incremental which is faster than pushing to array.
请帮助.
推荐答案
两个原因
- 您没有将递归的返回值添加到最终值.
- 增加原始值并不会在调用者函数的作用域内更改该值.
制作
if (stats.isDirectory())
{
var returnVal = getFilesRecursively(name, totalFiles, totalFilesArray);
totalFiles += returnVal.total_files;
}
此外,在方法开始时将totalFiles
值设置为0 .
Also, set the totalFiles
value to 0 in the beginning of the method.
这篇关于文件数未正确计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!