Javascript – Check if file exist in Gulp

gulpjavascriptnode.js

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

Best Solution

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.