Checking If A Particular Folder Is Present In SharePoint List Using JSOM

Introduction

 
In this blog we will learn about how to check if a particular folder is present in a Sharepoint list using JSOM.
 
Code Snippet
  1. function FolderExists(sitecollectionURL,ListNameTitle,folderName)  
  2. {  
  3.                 var deferred = $.Deferred();  
  4.                 var ClientContext = new SP.ClientContext(sitecollectionURL);  
  5.                 var web = ClientContext.get_web();  
  6.                 var ListName = web.get_ListNames().getByTitle(ListNameTitle);  
  7.                 var FolderCamlQuery = "<View Scope='RecursiveAll'><Query><Where><And><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>1</Value></Eq>"+  
  8.                 "<Eq><FieldRef Name='Title'/><Value Type='Text'>" + folderName + "</Value></Eq></And></Where></Query></View>";  
  9.                 var query = new SP.CamlQuery();  
  10.                 query.set_viewXml(FolderCamlQuery);  
  11.                 allItems = ListName.getItems(query);  
  12.                 ClientContext.load(allItems);  
  13.                   
  14.                 ClientContext.executeQueryAsync(  
  15.                                 Function.createDelegate(this,  
  16.                                                 function () { deferred.resolve(allItems); }),  
  17.                                 Function.createDelegate(this,  
  18.                                                 function (sender, args) { deferred.reject(sender, args); }));  
  19.                 return deferred.promise();  
  20. }  
  21.   
  22.   
  23.                   
  24.                 FolderExists(url,ListNameName,folderName).then(function(FolderFound)  
  25.                 {  
  26.                                 if(FolderFound.get_count() == 0)  
  27.                                 {  
  28.                                                 console.log("No folder found");  
  29.                                                 
  30.                                 }  
  31.                                 else  
  32.                                 {                
  33.                                     console.log("folder found");              
  34.                                                  
  35.                                 }  
  36.                 });  
  37.       
 Use the necessary Jquery.js and Jsom imports  before using this code. 
 
This code is very  straightforward if the condition FolderFound.get_count() >0 folder exists; otherwise the folder is not available.
 
That's it. Happy Coding :)