az rnd
az rnd

Reputation: 883

Next line should not execute if any errors occured

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

Answers (4)

Shubham Chaudhary
Shubham Chaudhary

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

Vivek Molkar
Vivek Molkar

Reputation: 3960

Following are the links you should look at:

  1. async programming
  2. callbacks link 1 and link 2

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

kRiZ
kRiZ

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

Andreas
Andreas

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

Related Questions