Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

renaming all files in a folder deletes all files

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. 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.mp3 means /User/John/Music/blah.mp3. It’s kind of like . or ... So you shouldn’t use it for the name.

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

  3. I think readdirSync returns an array of full paths, so you shouldn’t need to prefix file with __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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading