I am trying to rename all files in a folder but the current method im using is deleting all the files in that folder. Why is that happening and how can I fix it? Thanks in advance.
fs.readdirSync(path.join(__dirname, '..', 'blah')).forEach(file => {
fs.rename(path.join(__dirname, '..', 'blah', file), file.replaceAll(' ', '~'), (err) => {
if (err) throw err;
console.log('Rename complete!');
});
});
>Solution :
-
On unix systems (macOS, linux) the ~ symbol has a special meaning in a file path, you can’t use it for a file name.
So for example,
~/Music/blah.mp3means/User/John/Music/blah.mp3. It’s kind of like.or... So you shouldn’t use it for the name. -
When renaming a file, you need to give the full absolute path to that file in the new name, not just the name of the file.
So renaming
path.join(__dirname, 'blah.mp3')into'foo.mp3'would move the file from/User/John/a/b/blah.mp3(depending on where "__dirname" is) to/foo.mp3(at the root of your system). -
I think
readdirSyncreturns an array of full paths, so you shouldn’t need to prefixfilewith__dirname/../blah
Is it possible you’re trying to rename "files that don’t exist" (see point #3) into files that already exists (maybe your filename doesn’t contain ' ' or maybe '~' gets ignored because of point #1). And when renaming, the docs do mention:
In the case that newPath already exists, it will be overwritten.
(https://nodejs.org/api/fs.html#fsrenameoldpath-newpath-callback)