npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

sppurge

v3.0.1

Published

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

Downloads

281

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.