Skip to content

Instantly share code, notes, and snippets.

@kieranbarker
Last active April 14, 2022 19:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kieranbarker/50e7e56a0e63f9fc28c469995505bc21 to your computer and use it in GitHub Desktop.
Save kieranbarker/50e7e56a0e63f9fc28c469995505bc21 to your computer and use it in GitHub Desktop.
Asynchronously check if a file exists in Node.js.
//
// 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`));
{
"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"
}
@kieranbarker
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment