Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 357
Joseph Silber Avatar asked Feb 17 '13 03:02

Joseph Silber


People also ask

Does RM support regex?

For starters, rm doesn't accept a regular expression as an argument. Besides the wildcard * , every other character is treated literally.

How do I unlink multiple files in node?

Here's how you can do it as well as how to delete multiple ones using promises. So, all we need to do is call fs. unlink(), pass in the path to the file you want to delete and then pass a callback to be called after the file is deleted or the process errors out.

How do I unlink files in node?

js delete File with unlink. To delete a file in Node. js, we can use the unlink() function offered by the Node built-in fs module.


2 Answers

No there is no globbing in the Node libraries. If you don't want to pull in something from NPM then not to worry, it just takes a line of code. But in my testing the code provided in other answers mostly won't work. So here is my code fragment, tested, working, pure native Node and JS.

let fs = require('fs') const path = './somedirectory/' let regex = /[.]txt$/ fs.readdirSync(path)     .filter(f => regex.test(f))     .map(f => fs.unlinkSync(path + f)) 
like image 140
david.pfx Avatar answered Oct 02 '22 01:10

david.pfx


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

like image 29
user568109 Avatar answered Oct 02 '22 01:10

user568109