获取目录node-fs中所有具有信息(名称,类型,大小)的文件 [英] Get all files with infos(name, type, size) within directory node-fs

查看:673
本文介绍了获取目录node-fs中所有具有信息(名称,类型,大小)的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 路线 到要阅读的位置

I have a route to a location where I want to make a read

var route = ('F:\\uploads\\ponys');

var rez = fs.readdirSync(route, 'utf8');一起返回路由内所有文件(和文件夹)的数组.

with var rez = fs.readdirSync(route, 'utf8'); it return an Array of all files(and folders) inside of the route.

console.log(rez);
[ 'file.rtf',
  'Course.rtf',
  'extra.png',
  'ar102.rar',
  'New folder']

我想返回一个包含名称,类型和大小的JSON对象.我如何才能获得此信息:

I want to return an JSON Object which contains name, type and size. How I can proceed to obtain this:

{
  "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} 
  ]
}

推荐答案

对于目录中的每个文件,您尝试获取3个值:

For each file in a dir, you're trying to get 3 values:

  1. 文件名:已通过readdirSync获得)
  2. 文件扩展名:使用path.extname(filename)
  3. 文件大小:使用fs.statSync(filename).size
  1. file name: already got it with readdirSync)
  2. file extension: use path.extname(filename)
  3. file size: use fs.statSync(filename).size

1.获取文件扩展名示例

const path = require('path');
const extension = path.extname('index.html');
// 'html'

2.获取文件大小示例

const fs = require('fs');
const fileSizeInBytes = fs.statSync('file.html').size;

3.完整的方法

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("...")

这篇关于获取目录node-fs中所有具有信息(名称,类型,大小)的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆