How to Check if a File exists in Node using Async/Await
Table of Contents
Checking if a file exists is a common task in Node.
In this post, we'll learn how to check if a file exists in Node asynchronously by using async/await.
To do this, we'll use the fs
module, which is a Node module that provides a number of functions for working with the file system.
Since we're using async/await, we'll need to import the promises
module.
JAVASCRIPTimport { promises as fs } from "fs";
This gives us access to the fs
module, which we can use to check if a file exists.
We will be using the stat
function, which takes a path to a file and returns a promise.
We will then use await
to wait for the promise to resolve.
JAVASCRIPTimport { promises as fs } from "fs";
const fileExists = async path => !!(await fs.stat(path).catch(e => false));
Now that you have a function that can asynchronously check if a file exists, we can use it with the async
keyword.
JAVASCRIPTimport { promises as fs } from "fs";
const fileExists = async path => !!(await fs.stat(path).catch(e => false));
const path = "./content.txt";
const exists = await fileExists(path);
Conclusion
In this post, we've looked at how to check if a file exists in Node asynchronously by using the fs
module and async/await.
Hopefully, this content has been useful to you.
Happy coding!
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Sass
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js