Checking if a Folder Exists with PNP JS

The other day I was working on an SPFx solution that needed to verify if a folder existed, or else create it. Think of it as EnsureFolder, a throwback to one of my favorite SharePoint methods, EnsureUser.

Upon not seeing anything in a quick scan of Intellisense, I went to the PNP JS Documentation to check and see what the related property or method was that I needed to utilize, but I was surprised to find that there wasn’t a method or property to determine if a folder existed.

I checked with my colleague, Beau Cameron, to see what I might be missing, and he suggested explicitly selecting the ‘Exists’ property and utilizing that to determine if the folder path was valid. Sure enough, that worked like a charm, and thus, EnsureFolder, was born:

private async ensureFolder(uploadPath: string): Promise<any> {
        const folder = await sp.web.getFolderByServerRelativePath(uploadPath).select('Exists').get();
        if (!folder.Exists) {
            await sp.web.folders.addUsingPath(uploadPath);
        }
    }

I hope that this blog post helps you if you came across the same issue as I did.

Cheers,
Matt

Matt Jimison

Microsoft 365 Geek - Husband, father, lover of basketball, football, smoking / grilling, music, movies, video games, and craft beer!

One thought on “Checking if a Folder Exists with PNP JS

Leave a Reply

Your email address will not be published. Required fields are marked *