Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore hidden files in fs.readdir result

Tags:

node.js

In node application i need to get all the files in the directory except that hidden files. I have tried fs.readdir but it displaying hidden files also.

like image 929
sachin Avatar asked Sep 24 '13 05:09

sachin


People also ask

How do you list hidden files in your directory?

Open File Explorer from the taskbar. Select View > Options > Change folder and search options. Select the View tab and, in Advanced settings, select Show hidden files, folders, and drives and OK.

What is FS Dirent?

The fs. Dirent. isDirectory() method is an inbuilt application programming interface of class fs. Dirent within File System module which is used to check if the particular dirent describes a Directory or not. Syntax: const dirent.isDirectory()

What is FS Readdir?

The fs. readdir() method is used to asynchronously read the contents of a given directory. The callback of this method returns an array of all the file names in the directory. The options argument can be used to change the format in which the files are returned from the method.


2 Answers

Using the regex from this answer, this simple solution removes all hidden files from the result:

fs.readdir('/path/to/directory', (err, list) => {   list = list.filter(item => !(/(^|\/)\.[^\/\.]/g).test(item));    // Your code }); 
like image 195
birnbaum Avatar answered Sep 21 '22 10:09

birnbaum


You can use:

fs.readdir('/path/to/directory', function(err, list) {   list.forEach(function (filename) {     if(! /^\..*/.test(filename)) {       // display files     }   }); }); 
like image 22
saadel Avatar answered Sep 19 '22 10:09

saadel