sppurge

Delete files from SharePoint document libraries using Node.js without hassles

Usage no npm install needed!

<script type="module">
  import sppurge from 'https://cdn.skypack.dev/sppurge';
</script>

README

SPPurge - simple client to delete files from SharePoint document libraries

NPM

npm version Downloads Build Status Gitter chat

Node.js module for file deletion from SharePoint document libraries.

Supported SharePoint versions

  • SharePoint Online
  • SharePoint On-Prem (2019, 2016, 2013)

How to use

Install

npm install sppurge --save-dev

Usage

const sppurge = require('sppurge').default;

const context = {/*...*/};
const options = {/*...*/};

sppurge(context, options)
  .then(successHandler)
  .catch(errorHandler);

Arguments

Context
  • siteUrl - SharePoint site (SPWeb) url [string, required]
  • creds
    • username - user name for SP authentication [string, optional in case of some auth methods]
    • password - password [string, optional in case of some auth methods]

Additional authentication options:

Since SP client (sp-request), which is used in sppurge, had received additional SharePoint authentication methods, they are also supported in sppurge.

For more information please check node-sp-auth credential options and wiki pages.

Options
  • folder - relative folder in SharePoint to concat with filePath [string, optional, default: `` (empty string)]
  • filePath - relative file path, with extention [string, required in general, optional if localFilePath and localBasePath are both provided]
  • localFilePath - local full path to file [string, optional]
  • localBasePath - relative folder base path within project directory [string, optional]

The result file path is formed based on the following rule:

  • siteUrl + folder + filePath
  • If filePath is empty, then:
    • filePath = path.resolve(localFilePath).replace(path.resolve(localBasePath), '')

successHandler

The callback gets called upon successful file deletion.

errorHandler

The callback gets executed in case of an exception inside sppurge. Accepts error object as first argument for callback.

Basic usage example (delete a single file)

const sppurge = require('sppurge').default;

const context = { /* auth context */ };

const options = {
  folder: '/_catalogs/masterpage/spf/module_name',
  filePath: '/scripts/dummy-file.js'
};

sppurge(context, options)
  .then(deletionResults => {
    console.log('A file has been deleted');
  })
  .catch(err => {
    console.log('Core error has happened', err);
  });

Basic usage example (delete a folder)

const { Delete } = require('sppurge');

const context = { /* auth context */ };
const sppurge = new Delete();

sppurge.deleteFolder(context, '/sites/site/folder/repative/path')
  .then(deletionResults => {
    console.log('A folder has been deleted');
  })
  .catch(err => {
    console.log('Core error has happened', err);
  });

Within Gulp task

const gulp = require('gulp');
const watch = require('gulp-watch');      // Allows more than gulp.watch, is recommended
const spsave = require('gulp-spsave');    // Optional SPSave, but what is the reason to use SPPurge without SPSave?
const sppurge = require('sppurge').default;
const path = require('path');

const config = require('./gulp.config'); // Getting settings for SPPurge and SPSave

gulp.task('watch-assets', () => {
  return watch(config.watch.assets, function (event) {
    // Base local folder path, e.g. 'src' from which
    // project's files are mapped to SharePoint folder
    const watchBase = config.watch.base;

    // When file is deleted event value is "unlink"
    if (event.event === 'unlink') {
      const sppurgeOptions = {
        folder: config.sppurge.options.spRootFolder,
        filePath: path.resolve(event.path).replace(path.resolve(watchBase), '')
      };
      // OR:
      // const sppurgeOptions = {
      //   folder: config.sppurge.options.spRootFolder,
      //   localFilePath: event.path,
      //   localBasePath: watchBase
      // };
      sppurge(config.sppurge.context, sppurgeOptions)
        .then((res) => console.log(`File has been deleted: ${res}`))
        .catch((err) => console.log('Error', err));
    } else {
      // Saving files to SharePoint
      gulp.src(event.path, {
        base: watchBase
      }).pipe(
        spsave(
          // SPSave's core options, see more in spsave documentation
          config.spsave.coreOptions,
          // node-sp-auth / spsave credential object
          config.spsave.creds
        )
      );
    }
  });
});

Create React App usage scenario

Delete JS's build folder then upload all files from/build folder

One of the architectural decisions in CRA is using hashes as a part of assets filenames. This allows avoiding issues related to browser cache. However, it can be challenging in terms of deployment to SharePoint assets folders, as all filenames are different on each build. The further sample shows a simple use case approach of deleting files based on folder and name pattern.

const { AuthConfig } = require('node-sp-auth-config');
const sppurge = require('sppurge').default;
const spsave = require('spsave').spsave;

// client-side project's assets destination folder
const targetFolder = '_catalogs/masterpage/assets/cra-project';

const authConfig = new AuthConfig({
  configPath: './config/private.json',
  encryptPassword: true,
  saveConfigOnDisk: true
});

authConfig.getContext().then(({ siteUrl, authOptions: creds }) => {

  const deleteOptions = {
    folder: `${targetFolder}/static/js`,
    fileRegExp: new RegExp('(.*)/(.*)\.(js|map)', 'i'), // include .js, .map to delete
    // filePath: 'SiteAssets/trash.txt' // for single file deletion
  };

  const spsaveCoreOptions = {
    siteUrl,
    notification: true,
    checkin: true,
    checkinType: 2 // 0=minor, 1=major, 2=overwrite
  };

  const spsaveFileOptions = {
    glob: [ 'build/**/*.*' ],
    base: 'build',
    folder: targetFolder
  };

  return sppurge({ siteUrl, creds }, deleteOptions)
    .then(_ => console.log('=== Files Deleted ==='));
    .then(_ => spsave(spsaveCoreOptions, creds, spsaveFileOptions))
    .then(_ => console.log('=== Files Uploaded ==='));

}).catch(console.warn);

Passwords storage

To eliminate any local password storing if preferable to use any two-way hashing technique, like cpass.