user1708560
user1708560

Reputation:

Check nodejs path exists

I only want to know whether a path exists. Here's my code:

var path = require('path'); // exists path

Upvotes: 16

Views: 27075

Answers (1)

yasaricli
yasaricli

Reputation: 2533

The way to check if a file exists in the filesystem using the fs.existsSync() method:

const fs = require('fs')

const path = './file.txt';

if (fs.existsSync(path)) {
  //file exists
}

This method is synchronous, to check if a file exists in an asynchronous way, you can use fs.access(), which checks the existence of a file without opening it:

fs.access(path, fs.F_OK, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file exists
})

Upvotes: 21

Related Questions