-1

I am renaming files and are getting some weird behavior. It both works and throws an error.

This is the code:

var fs = require('fs');
var file = {
    rename: function(from, to){
        fs.rename(from, to, function (err) {
            if (err) throw err;
            console.log("[i] Renamed " + from + " to " + to);
        });
    }
}

When using it I get this console output:

main.js:1153 [i] Renamed E:\images\oldName.jpg to E:\images\newName.jpg
main.js:1152 Uncaught Error: ENOENT: no such file or directory, rename 'E:\images\oldName.jpg' -> 'E:\images\newName.jpg'
main.js:1152    (anonymous function)
fs.js:73        (anonymous function)

I don't understand what the problem is. The file is renamed anyway. Also, it doesn't happen if the file is moved to another folder.

Why is this happening and do I have to worry about it?

Blargmode
  • 1,015
  • 2
  • 10
  • 14

1 Answers1

0

The function is being called twice. That means the second time it's called the file is no longer there, leading to the 'no such file or directory'. I notice you're using windows which might also be part of the issue. Are you by any chance using fs.watch to call this function? You might be seeing an inherit problem in fs.watch under Windows duplicating events. If so, there's some example code that might help you.

Community
  • 1
  • 1
Alex Taylor
  • 8,343
  • 4
  • 25
  • 40
  • Not using fs.watch. But I found the problem looking for double calls. I was calling e.preventDefault on any disallowed input in an input field. This prevented the form from submitting when pressing enter. But when I manually triggered submit on Enter, it also bypassed the e.preventDefault call resulting in double submits. – Blargmode Aug 25 '15 at 00:36