Categories
JavaScript Answers

How to check if Node.js writeFileSync successfully wrote the file?

Spread the love

Sometimes, we want to check if Node.js writeFileSync successfully wrote the file.

In this article, we’ll look at how to check if Node.js writeFileSync successfully wrote the file.

How to check if Node.js writeFileSync successfully wrote the file?

To check if Node.js writeFileSync successfully wrote the file, we should wrap writeFileSync in a try-catch block.

For instance, we write

try {
  fs.writeFileSync(file, content, 'utf8');
} catch (e) {
  conso.e.log(e)
}

to call writeFileSync to write the content of the file to the file path with 'utf8' encoding.

If the write operation fails, an error will be thrown, and the error will be caught by the catch block.

Conclusion

To check if Node.js writeFileSync successfully wrote the file, we should wrap writeFileSync in a try-catch block.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *