Skip to content
Kyle Ross edited this page May 21, 2018 · 1 revision

When ModClean is installed locally to your project, you gain access to the programmatic API. Using the API allows for further customization of how ModClean works and allows you to integrate it into your build/CI process.

Install

npm install modclean --save-dev

Usage

const modclean = require('modclean');

Options

The options below can be used to modify how ModClean works.

cwd

(String) Default: process.cwd()
The path in which ModClean should recursively search through to find files to remove. If the path does not end with options.modulesDir, it will be appended to the path, allowing this script to run in the parent directory.

patterns

(Array[string]) Default ["default:safe"]
Patterns plugins/rules to use. Each value is either the full plugin module name (ex. modclean-patterns-pluginname) or just the last section of the module name (ex. pluginname). Plugins will usually have different rules to use, you can specify the rule name by appending a colon ':' and the rule name (ex. pluginname:rule). If a rule name is not provided, it will load the first rule found on the plugin. If you want to use all rules, you can use an asterisk as the rule name (ex. pluginname:*). By default, modclean-patterns-default is included. If you want to create your own plugin, see Custom Patterns Plugins.

additionalPatterns

(Array[string]) Default [] Additional custom glob patterns to include in the search. This will allow further customization without the need of creating your own patterns plugin.

ignorePatterns

(Array[string]) Default [] Custom glob patterns to ignore during the search. Allows skipping matched items that would normally be removed, which is good for patterns that match existing module names you wish not to be removed.

ignoreCase

(Boolean) Default true
Whether glob should ignore the case of the file names when searching. If you need to do strict searching, set this to false.

process

(Function) Default: null
Optional function to call before each file is deleted. This function can be used asynchronously or synchronously depending on the number of parameters provided. If the provided function has 0 or 1 parameters function(file), it is synchronous, if it has 2 parameters function(file, cb), it is asynchronous. When sync, you can return false to skip the current file being processed, otherwise when async, you can call the callback function cb(false) to skip the file. The file parameter is the current path with the filename appened of the file being processed.

emptyDirFilter

(Function) Default: function(file) { ... }
Optional filter function to use when checking if directories are empty. This function is used as an iterator, looping through each file found in a directory. Function is called with 1 parameter file which is a file name. If this function returns true, the file is considered a valid file that will not make the directory empty. If returns false, the file is considered invalid, thus being ignored. By default, this function filters out .DS_Store and Thumbs.db files.

modulesDir

(String|Boolean) Default: "node_modules"
The modules directory name to use when looking for modules. This is only used when setting the correct options.cwd path. If you do not want the modules directory to be appended to options.cwd, set this option to false. If options.cwd already ends with the value of this option, it will not be appended to the path.

removeEmptyDirs

(Boolean) Default: true
Whether to remove empty directories after the cleanup process. This is usually a safe option to use.

noDirs

(Boolean) Default: false
Set to true to skip directories from being deleted during the cleaning process.

dotFiles

(Boolean) Default true Set to false to skip dot files from being deleted during the cleaning process.

errorHalt

(Boolean) Default: false
Whether the script should exit with a filesystem error if one is encountered. This really only pertains to systems with complex permissions or Windows filesystems. The rimraf module will only throw an error if there is actually an issue deleting an existing file. If the file doesn't exist, it does not throw an error.

test

(Boolean) Default: false
Whether to run in test mode. If set to true everything will run (including all events), although the files will not actually be deleted from the filesystem. This is useful when you need to analyze the files to be deleted before actually deleting them.

followSymlink

(Boolean) Default: false - Since 2.1.1 Force deletion to be done also in symlinked packages (when using npm link).


Module

These are the methods and properties exported when calling const modclean = require('modclean');.

modclean([options][,cb])

Create a new ModClean instance. It's the same as calling new modclean.ModClean(). If a callback function is provided, it will automatically call the clean() method and therefore clean() should not be called manually. If you need to set event listeners, set the callback function in the clean() method instead.

Argument Type Required? Description Default
options Object No Optional options object to configure ModClean {}
cb Function No Optional callback function to call once cleaning complete. If not provided, clean() will not be called automatically null

Returns: new ModClean()

const modclean = require('modclean');

modclean(function(err, results) {
    // called once cleaning is complete.
    if(err) {
        console.error(err);
        return;
    }
    
    console.log(`${results.length} files removed!`);
});

modclean.defaults

(Object) - The default options used in all created ModClean instances. You may change the defaults at anytime if you will be creating multiple instances that need to use the same options.

modclean.ModClean([options][,cb])

Access to the ModClean class constructor.


ModClean Class

You can gain access to the ModClean Class using the following example:

const ModClean = require('modclean').ModClean;

Methods

ModClean([options][,cb])

Create instance of the ModClean class. Must be called with new.

Argument Type Required? Description Default
options Object No Optional options object to configure ModClean {}
cb Function No Optional callback function to call once cleaning complete. If not provided, clean() will not be called automatically null

Returns: this

const ModClean = require('modclean').ModClean;
    
// Create new instance
let MC = new ModClean();

clean([cb])

Runs the ModClean process. Only needs to be called if a callback function is not provided to the ModClean() constructor.

Argument Type Required? Description Default
cb Function No Optional callback function to call once cleaning complete. Called with err (error message if one occurred) and results (array of file paths removed) null

Returns: this

cleanEmptyDirs(cb)

Finds all empty directories and deletes them from options.cwd.

Argument Type Required? Description Default
cb Function Yes Callback function to call once complete. Called with err (error message if one occurred) and results (array of directories deleted)

_find(cb)

Internally used by ModClean to search for files based on the loaded patterns/rules.

Argument Type Required? Description Default
cb Function Yes Callback function to call once complete. Called with err (error message if one occurred) and files (array of file paths found)

_process(files, cb)

Internally used by ModClean to process each of the files. The processing includes running options.process and then calling _deleteFile().

Argument Type Required? Description Default
files Array[String] Yes Array of file paths to be deleted.
cb Function Yes Callback function to call once complete. Called with err (error message if one occurred) and results (array of file paths deleted)

_deleteFile(file, cb)

Internally used by ModClean to delete a file at the given path.

Argument Type Required? Description Default
file String Yes File path to be deleted
cb Function Yes Callback function to call once complete. Called with err (error message if one occurred) and files (the file path deleted). The callback will not receive an error if options.errorHalt = false

_findEmptyDirs(cb)

Internally used by ModClean to find all empty directories within options.cwd.

Argument Type Required? Description Default
cb Function Yes Callback function to call once complete. Called with err (error message if one occurred) and results (array of directories found)

_removeEmptyDirs(dirs, cb)

Internally used by ModClean to delete all empty directories provided.

Argument Type Required? Description Default
cb Function Yes Callback function to call once complete. Called with err (error message if one occurred) and results (array of directories deleted)

on(event, fn)

Creates an event handler on the ModClean instance using EventEmitter.

Argument Type Required? Description Default
event String Yes Event name to listen to (events are documented below)
fn Function Yes Function to call once the specified event is emitted

Properties

options

Type: Object
Compiled options object used by the ModClean instance.

errors

Type: Array
Array of error objects that contains all errors encountered during the process.

Events

The following events are emitted from the ModClean instance.

start

Emitted at the beginning of clean().

Argument Type Description
inst ModClean Access to the instance of ModClean

beforeFind

Emitted before _find() function starts.

Argument Type Description
patterns Array[String] Compiled list of glob patterns that will be used
globOpts Object The configuration object being passed into glob

files

Emitted once a list of all found files has been compiled from the _find() method.

Argument Type Description
files Array[String] Array of file paths found to be removed

process

Emitted at the start of the _process() function.

Argument Type Description
files Array[String] Array of file paths found to be removed

deleted

Emitted each time a file has been deleted from the file system by the _deleteFile() method.

Argument Type Description
file String File path that has been successfully deleted

finish

Emitted once processing and deletion of files has completed by the _process() method.

Argument Type Description
results Array[String] List of file paths that were successfully removed

complete

Emitted once the entire ModClean process has completed before calling the main callback function.

Argument Type Description
err Error Error object if one occurred during the process
results Array[String] List of file paths that were successfully removed

fileError

Emitted if there was an error thrown while deleting a file/folder. Will emit even if options.errorHalt = false.

Argument Type Description
err Error Error Object
err.file String The file that caused the error

error

Emitted if there was an error thrown while searching for files.

Argument Type Description
err Error Error Object

beforeEmptyDirs

Emitted before finding/removing empty directories.

afterEmptyDirs

Emitted after finding/removing empty directories.

Argument Type Description
results Array[String] Array of paths that were removed

emptyDirs

Emitted after a list of empty directories is found.

Argument Type Description
results Array[String] Array of paths that were found

deletedEmptyDir

Emitted after an empty directory is deleted.

Argument Type Description
dir String The directory path that was deleted

emptyDirError

Emitted if an error occurred while deleting an empty directory.

Argument Type Description
err Error Error Object
err.dir String The directory path that caused an error

Error Object

New in ModClean 2.1.0, errors are now stored in a new format on the class instance for later reference. The new format is also emitted out through the specific error events, but not through callback functions.

{
    error: new Error(),
    method: 'methodName'
    // ...
}

By default, all error objects will contain the properties error which will equal a JavaScript Error and method which will be a string method name in which the error occurred. Some errors may include additional properties such as file and dir to provide more context on what failed.


Examples

The folllowing examples will help you get started using the API. If you want to see a real-world example, see the source of the CLI.

Using Shortcut

const modclean = require('modclean');

modclean(function(err, results) {
    if(err) return console.error(err);
    
    console.log(`Successfully removed ${results.length} files/folders from the project`);
});

Using ModClean Class

const ModClean = require('modclean').ModClean;

let options = {
    // set the patterns to use
    patterns: ["default:safe", "default:caution"],
    
    // example process function, for ignoring files, you can use `ignorePatterns` option instead
    process: function(file) {
        // Skip .gitignore files (keeping them)
        if(file.match(/\.gitignore/i)) return false;
        
        return true;
    }
};

// If you pass a callback, it will automatically call `clean()`
let mc = new ModClean(options);

// Log errors
mc.on('error', function(err) {
    console.error(`Error in ${err.method}!`);
    console.error(err.error);
});

mc.on('files', function(files) {
    console.log(`About to delete ${files.length} files...`);
});

// This is optional, but can be used if you do not pass a callback to `clean()`
mc.on('complete', function(err, results) {
    if(err) {
        console.error('An error occurred during the process...');
        console.error(err);
    }
    
    console.log(`Successfully removed ${results.length} files/folders`);
});

// Start the clean process
mc.clean(function(err, results) {
    if(err) {
        console.error('An error occurred during the process...');
        console.error(err);
    }
    
    console.log(`Successfully removed ${results.length} files/folders`);
});

Advanced Usage

const path = require('path');
const ModClean = require('modclean').ModClean;
    
let mc = new ModClean({
    // Define a custom path
    cwd: path.join(process.cwd(), 'myApp/node/node_modules'),
    // Only delete patterns.safe patterns along with html and png files
    patterns: [modclean.patterns.safe, '*.html', '*.png'],
    // Run in test mode so no files are deleted
    test: true
});

mc.on('deleted', function(file) {
    // For every file deleted, log it
    console.log((mc.options.test? 'TEST' : ''), file, 'deleted from filesystem');
});

// Run the cleanup process without using the 'clean' function
mc._find(function(err, files) {
    if(err) return console.error('Error while searching for files', err);
    
    mc._process(files, function(err, results) {
        if(err) return console.error('Error while processing files', err);
        
        console.log('Deleted Files Total:', results.length);
        
        console.log(`${mc.errors.length} total errors occurred`);
    });
});