Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs - Check for hidden files

Tags:

node.js

I'm iterating a directory of files and was wondering if it's possible to test if a file is hidden or not. Currently, I'm just checking if file starts with a '.' or not. This works in Mac (and Linux, maybe), but, I'm wondering how I would do it on Windows? Also, will the period hide the file in all flavors of Linux?

Thanks!

Code:

var fs = require('fs');
fs.readdir('/path', function(err, list) {
   list.forEach(function(filename){
       var isHidden = /^\./.test(filename);
        // etc ...
    }); 
});
like image 352
user1155496 Avatar asked Jan 18 '12 05:01

user1155496


2 Answers

Did some quick testing using node 0.6.x on Windows 7. The setup was a folder containing 1 folder, 1 protected, 1 hidden and 1 file without special attributes.

I looped this folder and fetched the stats for the entries (using fs.stat(path, callback)), these are the results:

testfolder
fs.Stats.mode: 16895

test_hidden.txt
fs.Stats.mode: 33206

test_norm.txt
fs.Stats.mode: 33206

test_prot.txt
fs.Stats.mode: 33060

As you can see, one is able to differ between protected and hidden/normal files through the mode, but the hidden attribute is actually a real attribute and has nothing to do with the file mode.

In order to reliably identify hidden files on Windows, the node.js team would have to implement the GetFileAttributes() API on windows (like it's done by C++ or C#). AFAIK, this is not in the pipeline (at least i found nothing after some quick googling).

For your question concerning files being hidden in all flavors of unix when prefixed by a period: i didn't come across a distribution where this didn't work, so from my pov: yes.

like image 147
schaermu Avatar answered Oct 14 '22 15:10

schaermu


The regular expression to effectively detect hidden files and directory path in Unix would be a bit more complex owing to the possibility of their existence within a long path string.

The following tries to take care of the same.

/**
 * Checks whether a path starts with or contains a hidden file or a folder.
 * @param {string} source - The path of the file that needs to be validated.
 * returns {boolean} - `true` if the source is blacklisted and otherwise `false`.
 */
var isUnixHiddenPath = function (path) {
    return (/(^|\/)\.[^\/\.]/g).test(path);
};
like image 18
Shamasis Bhattacharya Avatar answered Oct 14 '22 16:10

Shamasis Bhattacharya