From 2fcf2829c59c2f664b693b6832b36b5e1fd52cbb Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 24 Jan 2023 09:54:37 -0600 Subject: [PATCH] Add Check If File Exists Before Reading It as a JavaScript TIL --- README.md | 3 +- .../check-if-file-exists-before-reading-it.md | 30 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 javascript/check-if-file-exists-before-reading-it.md diff --git a/README.md b/README.md index 221ee02..5c0a4ee 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1275 TILs and counting..._ +_1276 TILs and counting..._ --- @@ -394,6 +394,7 @@ _1275 TILs and counting..._ - [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md) - [Check Classes On A DOM Element](javascript/check-classes-on-a-dom-element.md) - [Check If A Number Is Positive Or Negative](javascript/check-if-a-number-is-positive-or-negative.md) +- [Check If File Exists Before Reading It](javascript/check-if-file-exists-before-reading-it.md) - [Check If Something Is An Array](javascript/check-if-something-is-an-array.md) - [Check The Password Confirmation With Yup](javascript/check-the-password-confirmation-with-yup.md) - [Compare The Equality Of Two Date Objects](javascript/compare-the-equality-of-two-date-objects.md) diff --git a/javascript/check-if-file-exists-before-reading-it.md b/javascript/check-if-file-exists-before-reading-it.md new file mode 100644 index 0000000..6501815 --- /dev/null +++ b/javascript/check-if-file-exists-before-reading-it.md @@ -0,0 +1,30 @@ +# Check If File Exists Before Reading It + +Let's say we are working on a script that tries to read in existing data from a +JSON data file. It is possible that data file hasn't been created and populated +yet. In order to account for that scenario, we need to check if the file +exists. If we try to read from a non-existant file, an error will be thrown. + +To prevent the script from error'ing out, we can use +[`fs.existsSync`](https://nodejs.org/api/fs.html#fsexistssyncpath) to check if +the given file path is an existing file. If we learn that the file does exist, +we can proceed with reading it. If not, we can skip the file read and react +accordingly. + +```javascript +import fs from 'fs' + +const nonExistantFile = 'non-existant.json' + +// set default in case file does not exists +let json = {} + +if(fs.existsSync(nonExistantFile)) { + const fileData = fs.readFileSync(nonExistantFile) + json = JSON.parse(fileData.toString()) +} + +console.log('JSON: ', json) +``` + +[source](https://flaviocopes.com/how-to-check-if-file-exists-node/)