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)?
For starters, rm doesn't accept a regular expression as an argument. Besides the wildcard * , every other character is treated literally.
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.
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.
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) { ... }); //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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With