check given path is valid or not in nodejs

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:


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:


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.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe