How to Check synchronously if file/directory exists in Node.js?

+1 vote

How can I synchronously check, using node.js, if a file or directory exists?

May 28 in Java-Script by kartik
• 16,230 points
62 views

1 answer to this question.

0 votes

Hello,

You can use fs.existsSync():

const fs = require("fs"); // Or `import fs from "fs";` with ESM
if (fs.existsSync(path)) {
    // Do something
}

You've specifically asked for a synchronous check, but if you can use an asynchronous check instead (usually best with I/O), use fs.promises.access if you're using async functions or fs.access if not:

In an async function:

try {
    await fs.promises.access("somefile");
    // The check succeeded
} catch (error) {
    // The check failed
}

Or with a callback:

fs.access("somefile", error => {
    if (!error) {
        // The check succeeded
    } else {
        // The check failed
    }
});
answered May 28 by Niroj
• 33,570 points

Related Questions In Java-Script

0 votes
1 answer

How to include csrf_token() in an external js file in Laravel?

Hello @kartik, To resolve this error you can ...READ MORE

answered Jun 11 in Java-Script by Niroj
• 33,570 points
81 views
0 votes
1 answer

How to access PHP session variables from jQuery function in a .js file?

Hello @kartik, You can produce the javascript file ...READ MORE

answered 1 day ago in Java-Script by Niroj
• 33,570 points
15 views
0 votes
1 answer

How can we create an HTTPS server in Node.js?

Hii, The Express API doc spells this out pretty clearly. I ...READ MORE

answered Apr 24 in Java-Script by Niroj
• 33,570 points
20 views
0 votes
1 answer

How do I pass command line arguments to a Node.js program?

Hello @kartik, If your script is called myScript.js ...READ MORE

answered May 5 in Java-Script by Niroj
• 33,570 points
77 views
0 votes
1 answer

What is Laravel framework? Why one should use Laravel?

Laravel is a PHP web-framework; it utilized ...READ MORE

answered Mar 17 in Laravel by Niroj
• 33,570 points
98 views
0 votes
1 answer

How to download and install Lavavel framework?

Hey @kartik, First you must have xampp install ...READ MORE

answered Mar 17 in Laravel by Niroj
• 33,570 points
92 views
0 votes
1 answer

Display Laravel in browser by using cmd promt?

Hello, First you need to have laravel install ...READ MORE

answered Mar 17 in Laravel by Niroj
• 33,570 points
38 views
0 votes
1 answer

How can we get started with Laravel through Xampp?

Hii, First you need to start Apache and ...READ MORE

answered Mar 17 in Laravel by Niroj
• 33,570 points
46 views
0 votes
1 answer

How do I turn a string to a json in Node.js?

Hello Kartik, Use the JSON function  JSON.parse(theString) ...READ MORE

answered Apr 24 in Java-Script by Niroj
• 33,570 points
37 views
0 votes
1 answer

How to access PHP session variables from jQuery function in a .js file?

Hello, You can produce the javascript file via ...READ MORE

answered Apr 29 in Java-Script by Niroj
• 33,570 points
565 views