Search code examples
node.jsfs

Get all files with infos(name, type, size) within directory node-fs


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

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

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']

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

Solution

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

    1. file name: already got it with readdirSync)
    2. file extension: use path.extname(filename)
    3. file size: use fs.statSync(filename).size

    1. Getting file extension example

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

    2. Getting file size example

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

    3. Complete approach

    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(route + file).size;
        response.push({ name: file, extension, fileSizeInBytes });
      }
      return response;
    }
    
    const { name, extension, fileSizeInBytes } = getFileInfoFromFolder("...")