我使用这个简单的async/await + fs Promises API(Node.js v14+)解决方案...它不依赖于外部库或生成新进程,这很好:
const path = require('path');
const { readdir, stat } = require('fs/promises');
const dirSize = async directory => {
const files = await readdir( directory );
const stats = files.map( file => stat( path.join( directory, file ) ) );
return ( await Promise.all( stats ) ).reduce( ( accumulator, { size } ) => accumulator + size, 0 );
}
使用方法:
( async () => {
const size = await dirSize( '/path/to/directory' );
console.log( size );
} )();
这种方法不使用任何循环结构来遍历目录,虽然它在映射/缩小数组。其他解决方案只是将递归抽象化到NPM包/C代码后面,所以应该都可以...
更新: 我以前的用例是基于上面的解决方案获取目录而不递归遍历子目录... 重新阅读问题后清楚原始发布者也想要子目录的大小。
如果有人正在寻找这个技巧,这应该就是解决方案;但从技术上讲,它并没有避免递归。感谢评论@Inigo!
const { readdir, stat } = require('fs/promises');
const { join } = require('path');
const dirSize = async dir => {
const files = await readdir( dir, { withFileTypes: true } );
const paths = files.map( async file => {
const path = join( dir, file.name );
if ( file.isDirectory() ) return await dirSize( path );
if ( file.isFile() ) {
const { size } = await stat( path );
return size;
}
return 0;
} );
return ( await Promise.all( paths ) ).flat( Infinity ).reduce( ( i, size ) => i + size, 0 );
}
使用方法:
( async () => {
const size = await dirSize( '/path/to/directory' );
console.log( size );
} )();
du -ksh /
需要很长时间,所以也许这个问题是...无意义的...我希望在这里有一个我所缺失的 Linux 东西。 - user772401du
就是做这个的,所以不,你无法绕过它。 - Ry-du
也会内部迭代所有文件。请澄清。 - Inigo