how to use the exists function from fs-extra in javascript

To use the exists function from fs-extra, you can follow the steps below:

  1. Install fs-extra module using npm:
index.tsx
npm install fs-extra
21 chars
2 lines
  1. Import the fs-extra module in your project:
index.tsx
const fs = require('fs-extra');
32 chars
2 lines
  1. Use the exists function to check whether a file or directory exists:
index.tsx
// Check if file exists
fs.pathExists('/path/to/file')
  .then(exists => console.log(exists))
  .catch(err => console.error(err))

// Check if directory exists
fs.pathExists('/path/to/directory')
  .then(exists => console.log(exists))
  .catch(err => console.error(err))
271 chars
10 lines

The exists function returns a promise that resolves to a boolean value indicating whether the specified file or directory exists or not. If the specified file or directory exists, the promise resolves to true, otherwise it resolves to false.

Note that you can also use the exists function synchronously if you don’t need a promise:

index.tsx
// Check if file exists synchronously
const exists = fs.existsSync('/path/to/file');
console.log(exists);

// Check if directory exists synchronously
const exists = fs.existsSync('/path/to/directory');
console.log(exists);
223 chars
8 lines

gistlibby LogSnag