Delete (unlink) files matching a regex Delete (unlink) files matching a regex javascript javascript

Delete (unlink) files matching a regex


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


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

require("glob").glob("*.txt", function (er, files) { ... });//orfiles = 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).


I have a very simple solution to do this. Read the directory in node.js using fs.readdir API. This will give an array of all the files in the directory. Once you have that array, iterate over it using for loop, apply regex.The below code will delete all files starting with "en" and extension ".js"

fs.readdir('.', (err, files)=>{   for (var i = 0, len = files.length; i < len; i++) {      var match = files[i].match(/en.*.js/);      if(match !== null)          fs.unlink(match[0]);   }});