Joseph Silber Joseph Silber - 1 month ago 29
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

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)?


You can look into glob

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

glob internally uses minimatch. It works by converting glob expressions into JavaScript RegExp objects.

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