NodeJS – Get the List of Site Collections in my Office 365 Tenant by PNP JS Search Query

Sathish Nadarajan
 
Solution Architect
October 12, 2021
 
Rate this article
 
Views
519

In the earlier articles, we saw how to get the context of SharePoint from the Node application. As part of that, let us see, how to get the list of site collections in my office 365 tenant.

The Index.ts will be as below.

import express, { Application, ErrorRequestHandler, Request, response, Response } from 'express';
import NodeFetchClient from 'node-pnp-js';
import * as pnp from 'sp-pnp-js';

const app: Application = express();
const PORT = process.env.PORT || 2000;

let url = "https://sppalsmvp.sharepoint.com/sites/MySiteCollection/";
let credentialOptions = {
    username: 'sathish@sppals.com',
    password: '****'
};

app.get("/", async (req: Request, res: Response): Promise<void> => {


    pnp.setup({
        sp: {
            fetchClientFactory: () => {
                return new NodeFetchClient(credentialOptions, url);
            }
        }
    });

    pnp.sp.search({
        Querytext: "contentclass:STS_Site", SelectProperties: ["Title","SPWebUrl", "SPSiteUrl", "WebTemplate"], RowLimit: 500, TrimDuplicates: false
    }).then((r) => {

        r.PrimarySearchResults.forEach((value) => {
            console.log(`${value.Title} - ${value.SPWebUrl} - ${value.WebTemplate}`);
       });

        res.send('success');
        
    }).catch(e=>{
       res.status(500).send(e); 
    });

});

app.use(function (err: any, req: Request, res: Response, next: ErrorCallback) {
    res.status(err.status || 500);
    res.send(err);
});

app.listen(PORT, (): void => {
    console.log(`Server Running here https://localhost:${PORT}`);
});

Happy Coding
Sathish Nadarajan

Author Info

Sathish Nadarajan
 
Solution Architect
 
Rate this article
 
Sathish is a Microsoft MVP for SharePoint (Office Servers and Services) having 15+ years of experience in Microsoft Technologies. He holds a Masters Degree in Computer Aided Design and Business ...read more
 

Leave a comment