# pathExists() function in fs-extra - NodeJS

Node.jsServer Side ProgrammingProgramming

#### Node.js Online Training

17 Lectures 2 hours

#### MERN Stack Full Ecommerce Site - Using React, Redux, Node.js

Best Seller

129 Lectures 19.5 hours

#### Using Clean architecture for Node.js API

89 Lectures 8 hours

## Introduction to Async pathExists()

This method will test whether the given path exists or not by checking with the file system. It will throw error in callback if the path does not exist.

### Syntax

pathExists(file[, callback])

### Parameters

• file – This is the path of the file that needs to be checked in all the file systems.

• callback – This function will give a callback if any error occurs.

### Example

• Check that fs-extra is installed before proceeding; if not, install fs-exra.

• You can use the following command to check whether fs-extra is installed or not.

npm ls fs-extra
• Create a pathExists.js and copy-paste the following code snippet into that file.

• Now, run the following command to run the following code snippet.

node pathExists.js

Code Snippet

const fs = require('fs-extra')

const file = '/tmp/dest/file2.txt'

// Checking Path with a callback:
fs.pathExists(file, (err, exists) => {
console.log(err) // => This will be null
console.log(exists) // => True if file exists
})

// CHecking path with Promise:
fs.pathExists(file)
.then(exists => console.log(exists)) // => True if file exists

// Checking path with async/await:
async function pathExistsExample (f) {
const exists = await fs.pathExists(f)
console.log(exists) // => True if file exists
}
pathExistsExample(file)

### Output

C:\Users\tutorialsPoint\> node pathExists.js
null
true
true
true

This method also ensures that the symlink exists. It creates the directory structure if does not exist.

### Syntax

pathExistsSync(file)

### Parameters

• file – This is the path of the file that needs to be checked in all the file systems.

### Example

• Check that fs-extra is installed before proceeding; if not, install fs-exra.

• You can use the following command to check whether fs-extra is installed or not.

npm ls fs-extra
• Create a pathExistsSyncExample.js and copy-paste the following code snippet into that file.

• Now, run the following command to run the following code snippet.

node pathExistsSyncExample.js

Code Snippet

const fs = require('fs-extra')

const file = '/tmp/dest2/file.txt'
const exists = fs.pathExistsSync(file)
console.log(exists)

### Output

C:\Users\tutorialsPoint\> node createSymlinkSyncExample.js
true
Updated on 28-Apr-2021 06:39:12