seriously
seriously

Reputation: 1377

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!');
  });
});

Upvotes: 0

Views: 232

Answers (1)

Sheraff
Sheraff

Reputation: 6742

  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)

Upvotes: 1

Related Questions