isaacs/rimraf

How to delete all files matching a glob pattern in nodejs

barisusakli opened this issue · 3 comments

I am probably missing something simple, trying to delete all files that start with a prefix.

async function deleteImages(uid) {
	const folder = path.join(nconf.get('upload_path'), 'profile');
	
	await Promise.all([
		rimraf(path.join(folder, `${uid}-profilecover*`), { glob: true }),
		rimraf(path.join(folder, `${uid}-profileavatar*`), { glob: true }),
	]);
}

The paths look like this:

D:\github\NodeBB\test\uploads\profile\51-profilecover* // passed to rimraf
// filenames in the folder `D:\github\NodeBB\test\uploads\profile`
[
  '51-profileavatar-1684768312077.png',
  '51-profileavatar-1684768312089.png',
  '51-profilecover-1684768312093.png',
  '51-profilecover-1684768312095.png'
]

Running the tests on windows maybe that matters.

Thanks

Glob patterns have to use / as the path separator, because \ is an escape character in glob syntax.

If you want to use \ as a path separator only (meaning you can't do stuff like \? to match a literal question-mark), you can do: rimraf(path.join(folder, ${uid}-profilecover*), { glob: { windowsPathsNoEscape: true } })

But a better approach is probably not to join the path to the pattern, and instead set the cwd:

rimraf(`${uid}-profilecover*`, { glob: { cwd: folder } })

You can also avoid the Promise.all and just put that in the pattern:

rimraf(`${uid}-profile{avatar,cover}*`, { glob: { cwd: folder }})

@isaacs thanks 👍🏼