0
votes

I am trying to find the structure of a folder or the list of all files and folders under a certain sharepoint site using the REST api. Is there a way to get the information in the "export to excel" sheet using the api?

1

1 Answers

0
votes

You can do by listing a folder and recursively check for more folders

const getFolderHierarchy = async (siteUrl, subsite, folder, authorization) => {
  logger.info('Fetching Hierarchy'.padEnd(padGap), folder.cyan);
  const folderPath = `('${makePath(null, subsite)}/${folder}')?$expand=Folders,Files`;
  let response = null;
  try {
    response = await fetch(`${makePath(siteUrl, subsite)}/_api/Web/GetFolderByServerRelativeUrl${folderPath}`, {
      method: 'GET',
      body: null,
      headers: getHeaders(authorization),
    }).catch(throwError);
    let folders = [folder];
    response = await response.json().catch(throwError);
    if (response.d.Folders.results.length) {
      for (const subFolder of response.d.Folders.results) {
        if (subFolder.Name !== 'Forms') { // Ignore forms
          folders.push(`${folder}/${subFolder.Name}`);
          folders = folders.concat(
            await getFolderHierarchy(siteUrl, subsite, `${folder}/${subFolder.Name}`, authorization)
              .catch(throwError),
          );
        }
      }
    }
    response = [...new Set(folders)];
  } catch (e) {
    throwError(e);
  }
  return response;
};

You will need this method to list all files in a particular folder

const getFiles = async (siteUrl, subsite, folder, authorization) => {
  logger.info('Listing Folder'.padEnd(padGap), folder.cyan);
  let response = null;
  try {
    response = await fetch(`${makePath(siteUrl, subsite)}/_api/web/getFolderByServerRelativeUrl('${folder}')/files`, {
      method: 'GET',
      body: null,
      headers: getHeaders(authorization),
    }).catch(throwError);
    response = await response.json().catch(throwError);
    response = response.d.results.map((file) => file.ServerRelativeUrl);
  } catch (e) {
    throwError(e);
  }
  return response;
};

Then when you have a list you can iterate and list all files

const folders = await getFolderHierarchy(siteUrl, subsite, remoteFolder, authorization).catch(throwError);
for (const folder of folders) {
  const files = await getFiles(siteUrl, subsite, folder, authorization).catch(throwError);
  for (const file of files) {
    //do something with the file
  }
}

You can find the complete source in here