Check if file exist in Gulp

22,157

Solution 1

You can use fs.access

fs.access('/etc/passwd', (err) => {
    if (err) {
        // file/path is not visible to the calling process
        console.log(err.message);
        console.log(err.code);
    }
});

List of available error codes here


Using fs.access() to check for the accessibility of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Doing so introduces a race condition, since other processes may change the file's state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.

Solution 2

You could add

var f;

try {
  var f = require('your-file');
} catch (error) {

  // ....
}

if (f) {
  console.log(f);
}

Solution 3

As of 2018, you can use fs.existsSync():

fs.exists() is deprecated, but fs.existsSync() is not. The callback parameter to fs.exists() accepts parameters that are inconsistent with other Node.js callbacks. fs.existsSync() does not use a callback.

See this answer for more details.

Solution 4

I believe fs-access package has been depreciated alternatively you may want to use:

path-exists.

file-exists.

Intracutions (path-exists):

npm install path-exists --save

const myFile = '/my_file_to_ceck.html';
const exists = pathExists.sync(myFile);
console.log(exists);

Intracutions (file-exists):

npm install file-exists --save


const fileExists = require('file-exists');
const myFile = '/my_file_to_ceck.html';
fileExists(myFile, (err, exists) => console.log(exists))

NPM Link: path exists

NPM Link: file exists

Share:
22,157
Caio Kawasaki
Author by

Caio Kawasaki

Updated on July 09, 2020

Comments

  • Caio Kawasaki
    Caio Kawasaki almost 4 years

    I need to check if a file exists in a gulp task, i know i can use some node functions from node, there are two:

    fs.exists() and fs.existsSync()

    The problem is that in the node documentation, is saying that these functions will be deprecated