nodejs 读取文件大小
时间: 2023-11-20 13:58:46 浏览: 596
以下是使用Node.js读取文件大小的方法:
```javascript
const fs = require('fs');
const path = require('path');
// 获取文件大小
function getFileSize(filePath) {
const stat = fs.statSync(filePath);
const fileSize = stat.size;
return fileSize;
}
// 获取文件夹大小
function getFolderSize(folderPath) {
let folderSize = 0;
const files = fs.readdirSync(folderPath);
files.forEach(function(file) {
const filePath = path.join(folderPath, file);
const stat = fs.statSync(filePath);
if (stat.isFile()) {
folderSize += stat.size;
} else if (stat.isDirectory()) {
folderSize += getFolderSize(filePath);
}
});
return folderSize;
}
// 示例
const filePath = 'example.txt';
const folderPath = 'exampleFolder';
console.log(`文件 ${filePath} 的大小为 ${getFileSize(filePath)} 字节`);
console.log(`文件夹 ${folderPath} 的大小为 ${getFolderSize(folderPath)} 字节`);
```
阅读全文