I want to get list of filenames in folder using node.js along with other details such as

  • filename
  • created date
  • filesize

So which procedure should I follow to get details of files

  • node js fs readdirsync
  • fs read directory

So, If one has an idea for a listing of filenames please give me node.js fs example.

Bhaskar Monitor Asked on February 20, 2017 in Programming.
Add Comment
  • 2 Answer(s)

    I would like to share a solution to get a list of filenames in a folder using node.js.

    We can read a directory and get a list of files within it by using fs.readdir.

    Syntx:

    
     fs.readdir(path[, options], callback
    
      • path <String> | <Buffer>
      • options <String> | <Object>
      • encoding <String> default = 'utf8'
      • callback <Function>

    fs.statSync[https://nodejs.org/api/fs.html#fs_fs_statsync_path] give us details of files like created on, file size (Bytes), last access time, last change time, last modify theme can be accessed.

    fs.statSync returns an array of files properties. Like
    var stats = fs.statSync(“/Os/”+file);
    stats[“size”] = size of file in Bytes
    stats[“atime”] = Last file access time
    stats[“mtime”] = Last modify time of file when content of file is changed
    stats[“birthtime”] = file created time

    Example:

    
     var fs = require("fs");
         //Get files within the Os Directory
             fs.readdir("/Os/", (err,files) => {
             files.forEach(file => {
                 var stats = fs.statSync("/Os/"+file);
                 console.log("==============================================>");
                 console.log("Name: " + file + " Size: " + stats["size"]);
                 console.log("Last Access:" + stats["atime"] + " Modify Time: " + stats["mtime"]);
                 console.log("Created On : "+stats["birthtime"]);
                 console.log("==============================================>");
             });
     });
     

    Bhaskar Monitor Answered on February 22, 2017.
    Add Comment

    You can use the fs.readdir

    const testFolder = ‘./tests/’;
    const fs = require(‘fs’);

    fs.readdir(testFolder, (err, files) => {
    files.forEach(file => {
    console.log(file);
    });
    });

    if you are looking for Node.js development services, then hire the services of a trustworthy company with great knowledge in this field for your next project.

    gurutechnolabs Default Answered on March 6, 2020.
    Add Comment
  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.