Reputation: 883
var fs = require("fs");
fs.rename("newFile.txt", "sample.txt", (error) => {
console.log("error")
})
console.log("success")
This is my code. If any error occurred during rename the file, the program will not go to next line.
But now I am getting success message if any error occurred also.
How to fix this issue. Please anyone help.
Thanks in advance.
Upvotes: 0
Views: 552
Reputation: 499
This happens because of asynchronous function execution. If you want async execution, Andreas is correct. But if you want synchronous execution, use following code:
fs.renameSync("newFile.txt, "sample.txt");
console.log("success");
Upvotes: 1
Reputation: 3960
Following are the links you should look at:
Following is the right way:
var fs = require('fs');
fs.rename('newFile.txt', 'sample.txt', error => {
if (error) { // handle errors here
console.log('error');
} else { // it is success
console.log('success');
}
});
Upvotes: 1
Reputation: 815
May be you should change as below:
fs.rename("newFile.txt", "sample.txt", (error) => {
if(error) throw error;
console.log("error")
})
Upvotes: 0
Reputation: 2521
That happened because you have asynchronous function execution. It will execute the next statement without waiting for the current statement to finish. Hence, you usually get the console.log("success")
being executed (unless the error
is being returned earlier). To prevent that, do a check on the error
and print whether it succeeded or not based on that. For example:
var fs = require("fs");
fs.rename("newFile.txt", "sample.txt", (error) => {
if (error === null) {
console.log("success")
} else {
console.log("error")
}
})
Upvotes: 1