Last active
April 14, 2022 19:11
-
-
Save kieranbarker/50e7e56a0e63f9fc28c469995505bc21 to your computer and use it in GitHub Desktop.
Asynchronously check if a file exists in Node.js.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Callback API | |
// | |
import { access, constants } from 'fs'; | |
const file = 'package.json'; | |
access(file, constants.F_OK, error => { | |
if (error) { | |
console.log(`${file} does not exist`); | |
} else { | |
console.log(`${file} exists`); | |
} | |
}); | |
// | |
// Promises API | |
// | |
// import { constants } from 'fs'; | |
// import { access } from 'fs/promises'; | |
// const file = 'package.json'; | |
// access(file, constants.F_OK) | |
// .then(() => console.log(`${file} exists`)) | |
// .catch(error => console.log(`${file} does not exist`)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "file_exists", | |
"version": "1.0.0", | |
"description": "Asynchronously check if a file exists.", | |
"private": true, | |
"main": "file_exists.js", | |
"type": "module", | |
"scripts": { | |
"start": "node file_exists.js", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"keywords": [], | |
"author": "Kieran Barker <[email protected]> (https://barker.codes/)", | |
"license": "MIT" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Read the blog post.