Asynchronously check if a file exists in Node.js.
This file contains 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 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 <kieran@barker.codes> (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.