Joseph Silber Joseph Silber - 3 months ago 66
Javascript Question

Delete (unlink) files matching a regex

I want to delete several files from a directory, matching a regex. Something like this:

// WARNING: not real code
require('fs').unlink(/script\.\d+\.js$/);





Since
unlink
doesn't support regexes, I'm using this instead:

var fs = require('fs');

fs.readdir('.', (error, files) => {
if (error) throw error;

files.filter(name => /script\.\d+\.js$/.test(name)).forEach(fs.unlink);
});


which works, but IMO is a little more complex than it should be.




Is there a better built-in way to delete files that match a regex (or even just use wildcards)?

Answer

You can look into glob https://npmjs.org/package/glob

require("glob").glob("*.txt", function (er, files) { ... });
//or
files = require("glob").globSync("*.txt");

glob internally uses minimatch. It works by converting glob expressions into JavaScript RegExp objects. https://github.com/isaacs/minimatch

You can do whatever you want with the matched files in the callback (or in case of globSync the returned object).

Comments