Skip to content

Commit 2fcf282

Browse files
committed
Add Check If File Exists Before Reading It as a JavaScript TIL
1 parent e2cbec1 commit 2fcf282

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186).
1212

13-
_1275 TILs and counting..._
13+
_1276 TILs and counting..._
1414

1515
---
1616

@@ -394,6 +394,7 @@ _1275 TILs and counting..._
394394
- [Character Codes from Keyboard Listeners](javascript/character-codes-from-keyboard-listeners.md)
395395
- [Check Classes On A DOM Element](javascript/check-classes-on-a-dom-element.md)
396396
- [Check If A Number Is Positive Or Negative](javascript/check-if-a-number-is-positive-or-negative.md)
397+
- [Check If File Exists Before Reading It](javascript/check-if-file-exists-before-reading-it.md)
397398
- [Check If Something Is An Array](javascript/check-if-something-is-an-array.md)
398399
- [Check The Password Confirmation With Yup](javascript/check-the-password-confirmation-with-yup.md)
399400
- [Compare The Equality Of Two Date Objects](javascript/compare-the-equality-of-two-date-objects.md)
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Check If File Exists Before Reading It
2+
3+
Let's say we are working on a script that tries to read in existing data from a
4+
JSON data file. It is possible that data file hasn't been created and populated
5+
yet. In order to account for that scenario, we need to check if the file
6+
exists. If we try to read from a non-existant file, an error will be thrown.
7+
8+
To prevent the script from error'ing out, we can use
9+
[`fs.existsSync`](https://nodejs.org/api/fs.html#fsexistssyncpath) to check if
10+
the given file path is an existing file. If we learn that the file does exist,
11+
we can proceed with reading it. If not, we can skip the file read and react
12+
accordingly.
13+
14+
```javascript
15+
import fs from 'fs'
16+
17+
const nonExistantFile = 'non-existant.json'
18+
19+
// set default in case file does not exists
20+
let json = {}
21+
22+
if(fs.existsSync(nonExistantFile)) {
23+
const fileData = fs.readFileSync(nonExistantFile)
24+
json = JSON.parse(fileData.toString())
25+
}
26+
27+
console.log('JSON: ', json)
28+
```
29+
30+
[source](https://flaviocopes.com/how-to-check-if-file-exists-node/)

0 commit comments

Comments
 (0)