LogoLogo
  • Introduction
  • Our Packages
    • sp-rest-proxy
    • node-sp-auth-config
    • generator-sppp
    • sp-build-tasks
    • sp-pnp-node
    • sp-jsom-node
    • sppull
    • sp-download
    • sppurge
    • sp-live-reload
    • sp-screwdriver
    • cpass
Powered by GitBook
On this page
  • Supported SharePoint versions
  • How to use

Was this helpful?

  1. Our Packages

sppurge

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

Previoussp-downloadNextsp-live-reload

Last updated 5 years ago

Was this helpful?

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

Supported SharePoint versions

  • SharePoint Online

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

How to use

Install

npm install sppurge

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 communication module (sp-request), which is used in sppurge, had received additional SharePoint authentication methods, they are also supported in sppurge.

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]

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

Callback gets called upon successful file deletion.

errorHandler

Callback gets executed in case of 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
    var watchBase = config.watch.base;

    // When file is deleted event value is "unlink"
    if (event.event === 'unlink') {
      var 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.message));
    } 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 decision 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 term 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(err => console.log(err.message));

Passwords storage

For more information please check node-sp-auth and .

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

credential options
wiki pages
cpass
NPM
npm version
Build Status
Gitter chat
Downloads