-
Notifications
You must be signed in to change notification settings - Fork 13
API v2
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.
npm install modclean --save-dev
const modclean = require('modclean');
The options below can be used to modify how ModClean works.
(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.
(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.
(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.
(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.
(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
.
(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.
(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.
(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.
(Boolean) Default: true
Whether to remove empty directories after the cleanup process. This is usually a safe option to use.
(Boolean) Default: false
Set to true
to skip directories from being deleted during the cleaning process.
(Boolean) Default true
Set to false
to skip dot files from being deleted during the cleaning process.
(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.
(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.
(Boolean) Default: false
- Since 2.1.1
Force deletion to be done also in symlinked packages (when using npm link).
These are the methods and properties exported when calling const modclean = require('modclean');
.
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!`);
});
(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.
Access to the ModClean class constructor.
You can gain access to the ModClean Class using the following example:
const ModClean = require('modclean').ModClean;
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();
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
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) |
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) |
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) |
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
|
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) |
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) |
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 |
Type: Object
Compiled options object used by the ModClean instance.
Type: Array
Array of error objects that contains all errors encountered during the process.
The following events are emitted from the ModClean
instance.
Emitted at the beginning of clean()
.
Argument | Type | Description |
---|---|---|
inst |
ModClean | Access to the instance of ModClean |
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
|
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 |
Emitted at the start of the _process()
function.
Argument | Type | Description |
---|---|---|
files |
Array[String] | Array of file paths found to be removed |
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 |
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 |
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 |
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 |
Emitted if there was an error thrown while searching for files.
Argument | Type | Description |
---|---|---|
err |
Error | Error Object |
Emitted before finding/removing empty directories.
Emitted after finding/removing empty directories.
Argument | Type | Description |
---|---|---|
results |
Array[String] | Array of paths that were removed |
Emitted after a list of empty directories is found.
Argument | Type | Description |
---|---|---|
results |
Array[String] | Array of paths that were found |
Emitted after an empty directory is deleted.
Argument | Type | Description |
---|---|---|
dir |
String | The directory path that was deleted |
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 |
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.
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.
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`);
});
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`);
});
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`);
});
});
Information:
Wiki Home
Migrating to 3.x
Migrating to 2.x
Benchmarks
Custom Pattern Plugins
Documentation (v3):
CLI Documentation
API Documentation
Documentation (v2):
CLI Documentation
API Documentation