我有 路线 到我想要阅读的位置
var route = ('F:\\uploads\\ponys');
使用var rez = fs.readdirSync(route, 'utf8');
它会返回路径内所有文件(和文件夹)的数组。
console.log(rez);
[ 'file.rtf',
'Course.rtf',
'extra.png',
'ar102.rar',
'New folder']
我想返回一个包含名称,类型和大小的JSON对象。我如何才能获得这个:
{
"files":[
{"name": "file", "type": "rtf", "size": 3445}, [or with "."(.rtf)]
{"name": "Course", "type": "rtf", "size": 900},
{"name": "extra", "type": "png", "size": 2424},
{"name": "ar102", "type": "rar", "size": 340432},
{"name": "New folder", "type": "", "size": 123456789}
]
}
答案 0 :(得分:3)
对于目录中的每个文件,您都试图获得3个值:
readdirSync
)path.extname(filename)
fs.statSync(filename).size
const path = require('path');
const extension = path.extname('index.html');
// 'html'
const fs = require('fs');
const fileSizeInBytes = fs.statSync('file.html').size;
const path = require('path');
const fs = require('fs');
const getFileInfoFromFolder = (route) => {
const files = fs.readdirSync(route, 'utf8');
const response = [];
for (let file of files) {
const extension = path.extname(file);
const fileSizeInBytes = fs.statSync(file).size;
response.push({ name: file, extension, fileSizeInBytes });
}
return response;
}
const { name, extenstion, fileSizeInBytes } = getFileInfoFromFolder("...")