pnp / pnpjs

Fluent JavaScript API for SharePoint and Microsoft Graph REST APIs
https://pnp.github.io/pnpjs/
Other
740 stars 300 forks source link

How can I get a list of all folders in a document library? #3038

Closed SharonGilmore closed 1 month ago

SharonGilmore commented 1 month ago

What version of PnPjs library you are using

3.x

Minor Version Number

24.0

Target environment

SharePoint Framework

Additional environment details

I'm creating a Web Part using SPFx

Question/Request

I have a site with a Document Library called "Oversight". It has 3 folders, "Section 1", "Revamp" and "Admin". Each one currently has a couple of sample documents in it.

I want to get a list of the folders, and then all the files and folders within each one.

So far I'm doing

const res: IDocumentLibraryInformation[] = await spCache.site.getDocumentLibraries("https://{path to site}");

This returns 4 items; one for each folder plus "Oversight". However, there's nothing to indicate which is the top folder. Is there a way to get that information?

How can I get the list of documents within each folder (and also any folders that might be inside)? Thanks for any help.

jasonalex13 commented 1 month ago

Hi @SharonGilmore

Here's how I would do it..

// Here is where we get the folders, each will have a "ServerRelativeUrl" that can be used to reference the folder
const folders = await this.sp.web.lists.getByTitle("Assets").rootFolder.folders();

// Iterate through each folder
for (const folder of folders) {
    // Get the folders/files from the folder
    const folderData = await this.sp.web.getFolderByServerRelativePath(folder.ServerRelativeUrl).expand(`Folders`, `Files`)();

    // Files will be inside folderData.files as an array
}
SharonGilmore commented 1 month ago

Thanks for that; that seems to work!

github-actions[bot] commented 1 month ago

This issue is locked for inactivity or age. If you have a related issue please open a new issue and reference this one. Closed issues are not tracked.