Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript regex to ignore sub directories for chokidar

Currently using Chokidar to do file watching on a file structure. I have a requirement to watch a specific directory, but ignore any sub-directories created in that directory.

For example,
/var/app/current/somedir

I would watch any file created in somedir. However if a directory were created in somedir, then I want to ignore it recursively, thus also ignoring anything else created under it.

chokidar.watch(configuration.theDir, {
        ignored: `/\\var\\app\\current\\somedir\\<match anything here, except other directories!>\\<anything here would be ignored and further down...>/`,
        awaitWriteFinish: {
            stabilityThreshold: 2000,
            pollInterval: 100
        }
}).on('add', (file, details) => {
    // console.log(file, path);
});

The struggle is real for me to figure out how to properly implement a regex to do this. Unfortunately the directories that get created are random and the name is not known beforehand. Is this even possible to do?

like image 552
dvsoukup Avatar asked Oct 29 '25 20:10

dvsoukup


1 Answers

This regex expression will match everything that is a directory or belongs in a subdirectory of the base (directory defined by a following slash /).

For your example, the base is: /var/app/current/somedir

Regex: /^\/var\/app\/current\/somedir\/.*[\/].*$/i

Test:

var tests = [
    '/var/app/current/somedir/fileOrFolder.txt',
    '/var/app/current/somedir/fileOrFolder/',
    '/var/app/current/somedir/fileOrFolder/ssads/sad.s',
    '/var/app/current/somedir/fileOrFolder.sd/sdasda.asda/',
    '/var/app/current/somedir/fileOrFolder.txt',
    '/var/app/current/somedir/fileOrFolder'
]

for (var ii = 0, nn = tests.length; ii < nn; ii++)
{
    if (/^\/var\/app\/current\/somedir\/.*[\/].*$/i.test(tests[ii]))
    {
        console.log('"'+tests[ii]+'"', 'Matched, so ignored.');
    }
    else
    {
        console.log('"'+tests[ii]+'"', 'Not matched, so watch.');
    }
}

Prints the following in JavaScript console:

/*
 * "/var/app/current/somedir/fileOrFolder.txt" Not matched, so watch.
 * "/var/app/current/somedir/fileOrFolder/" Matched, so ignored.
 * "/var/app/current/somedir/fileOrFolder/ssads/sad.s" Matched, so ignored.
 * "/var/app/current/somedir/fileOrFolder.sd/sdasda.asda/" Matched, so ignored.
 * "/var/app/current/somedir/fileOrFolder.txt" Not matched, so watch.
 * "/var/app/current/somedir/fileOrFolder" Not matched, so watch.
*/
like image 52
Joseph Shih Avatar answered Oct 31 '25 10:10

Joseph Shih



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!