Check If file / folder is exists or not using nodejs

 Posted On  | Yashwant Chavan 

In this tutorial, You will learn how to check If file / folder is exists or not using nodejs. fs.exists() is deprecated. You can use fs.stat() or fs.access() instead.

syntax - Asynchronous

fs.exists(path, callback)

Test whether or not the given path exists by checking with the file system. Then call the callback argument with either true or false.

path <String> | <Buffer> filename or file descriptor

callback - <Function>

syntax - Synchronous

fs.existsSync(path)

path <String> | <Buffer> filename or file descriptor

file exists ? check asynchronously

var fs = require('fs');

fs.exists('c:\\hello.txt', function(exists) {
    console.log("file exists ? " + exists);
});

fs.exists('c:\\demo', function(exists) {
    console.log("folder exists ? " + exists);
});

fs.exists('c:\\cat.jpg', function(exists) {
    console.log("file exists ? " + exists);
});

output

file exists ? true
folder exists ? true
file exists ? false

file exists ? check synchronously

var fs = require('fs');
var exists = fs.existsSync('c:\\hello.txt');
console.log('file exists ? ' + exists);

output

file exists ? true


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0275 seconds.