Skip to content
the poor coder

check given path is valid or not in nodejs

Poor Man
Published
Reading time
1 min read
On this page

Validating a Path in Node.js#

As a web developer, I often work with Node.js and need to validate paths to ensure that they exist before executing code. In Node.js, we can use the 'fs' module to check if a given path is valid or not.

Method 1 - Using fs.access()#

The 'fs.access()' method is used to check if a file or directory exists or not. It takes two arguments - the path to the file or directory and a callback function. The callback function takes an error object as its argument. If the file or directory exists, the error object is null. Otherwise, it contains information about the error.

Code:

Text

const fs = require('fs');

const path = '/path/to/file';

fs.access(path, (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Path exists');
  }
});

Method 2 - Using fs.existsSync()#

The 'fs.existsSync()' method is used to check if a file or directory exists or not. It takes one argument - the path to the file or directory. If the file or directory exists, it returns true. Otherwise, it returns false.

Code:

Text

const fs = require('fs');

const path = '/path/to/file';

if (fs.existsSync(path)) {
  console.log('Path exists');
} else {
  console.error('Path does not exist');
}

Both methods are useful in their own way but it's up to you which one you prefer to use. The first method is asynchronous, so it's better suited for cases where you need to perform other operations while validating the path. The second method is synchronous, so it's better suited for cases where you need the validation to be completed before moving on to the next operation.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC