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. ClientContext.executeQueryAsync(
  14. Function.createDelegate(this,
  15. function () { deferred.resolve(allItems); }),
  16. Function.createDelegate(this,
  17. function (sender, args) { deferred.reject(sender, args); }));
  18. return deferred.promise();
  19. }
  20. FolderExists(url,ListNameName,folderName).then(function(FolderFound)
  21. {
  22. if(FolderFound.get_count() == 0)
  23. {
  24. console.log("No folder found");
  25. }
  26. else
  27. {
  28. console.log("folder found");
  29. }
  30. });
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 :)