Introduction
In this article, you will learn how to retrieve the folders from SharePoint sites and libraries, using PnP JavaScript Core Library.
Note: SharePoint libraries are considered as the folders. The operations can be executed by adding the script references on the content editor Web part or any normal custom Web part from the site collections or sites or sub sites. The results will be retrieved only from the corresponding site or site collection, which the site is part of.
The PnP JavaScript Core library is supported by SharePoint 2013, SharePoint 2016 On Premises, and Office 365 versions. The following operations are tested on SharePoint 2013 and Office 365 environments:
Prerequisite
The required JavaScript Core library references for executing any operations, using PnP, are:
- es6-promise.js
- fetch.js
- pnp.js or pnp.min.js
The script references should be called from the Web parts, only in the order given above.
Note: You can download the references from my initial article about PnP JavaScript Core library.
I explained about the necessity of using the promise and retrieving JS references in the article's link, mentioned above. You can also download these references from the Github site as well.
We can set up the header before executing any operation. This is required when you want the response type to be predetermined. Let us see how we can get the JSON data as a response. This has to be done once, before initiating all the requests on the page. This step is not mandatory for O365 environment.
The code snippet, given below, shows the setting up of header:
- $pnp.setup({
- headers: {
- "Accept": "application/json; odata=verbose",
- },
- });
Retrieve Folders from SharePoint Site
In this section, you will learn how to retrieve all the folders available on the site, using PnP JavaScript Core Library.
First, we need to retrieve the web object and then the folders collection. Get method is used to retrieve all the information of folders.
The following code snippet helps in retrieving all the folders and properties from a site.
- // Retrieve Folders from Current Site
- $pnp.sp.web.folders.get().then(function(data){
- console.log("There are totally " + data.length + " folders available on the current site");
- // Displays results on debugger console
- for(var i=0; i < data.length; i++){
- console.log(data[i].Name + " - " + data[i].ServerRelativeUrl);
- }
- }).catch(function(data){
- console.log(data);
- });

Jussi PaloPosted Sep 7, 2018, 1:57 AM
But you're only getting 1st level folders, right?
Ram krishPosted Aug 12, 2016, 7:11 AM
Good
Vignesh ManiPosted Aug 11, 2016, 11:33 AM
Nice