Grunt plugin for cleaning files and folders with safety features and flexible configuration options
npx @tessl/cli install tessl/npm-grunt-contrib-clean@2.0.0Grunt Contrib Clean is a Grunt plugin that provides safe and flexible file and folder deletion functionality for build processes and project maintenance. It offers comprehensive protection features, multiple configuration formats, and detailed logging for reliable cleanup operations in Grunt workflows.
npm install grunt-contrib-clean --save-devThe plugin is designed to be used as a Grunt task plugin. There are no direct exports to import - instead, the plugin registers tasks with the Grunt instance.
In a Gruntfile:
// Load the plugin to register the 'clean' task
grunt.loadNpmTasks('grunt-contrib-clean');
// Alternative: if using load-grunt-tasks
require('load-grunt-tasks')(grunt);Module Structure:
// The main module exports a single registration function
const cleanPlugin = require('grunt-contrib-clean');
// This exports: function(grunt) { /* registers 'clean' task */ }The plugin automatically registers the clean multi-task when loaded, making it available for configuration and execution.
// Simple array of paths to clean
clean: ['path/to/dir/one', 'path/to/dir/two']
// Configure the task in your Gruntfile
grunt.initConfig({
clean: {
build: ['tmp/', 'dist/js/'],
release: ['dist/']
}
});
// Run the task
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.registerTask('cleanup', ['clean:build']);Grunt Contrib Clean is built around Grunt's multi-task system and follows the standard Grunt plugin architecture:
clean multi-taskthis.filesSrc) to handle glob patterns and file listsasync library for serial processingrimraf for actual deletionKey dependencies:
eachSeries for processing files sequentially to avoid overwhelming the filesystemThe plugin exports a single function that registers the clean task with Grunt.
/**
* Main module export - function that registers the clean task
* @param {Object} grunt - Grunt instance
*/
module.exports = function(grunt) {
// Registers the 'clean' multi-task
};The plugin registers a multi-task called 'clean' that removes files and directories specified in the configuration.
// Task registration (handled automatically by grunt.loadNpmTasks)
grunt.registerMultiTask('clean', 'Clean files and folders.', function() {
// Task implementation
});Simple array of file/directory paths for straightforward cleanup.
// Gruntfile configuration
clean: string[]Usage Examples:
// Clean specific directories
clean: ['tmp/', 'dist/css/', 'dist/js/']
// Clean with glob patterns
clean: ['build/**/*', 'temp/*.tmp']Object with named targets, each containing an array of paths to clean.
// Gruntfile configuration
clean: {
[targetName: string]: string[]
}Usage Examples:
clean: {
build: ['tmp/', 'dist/js/'],
release: ['dist/', 'reports/'],
css: ['dist/css/*.css', '!dist/css/vendor.css']
}Object with named targets containing detailed configuration including per-target options.
// Gruntfile configuration
clean: {
[targetName: string]: {
src: string[];
options?: CleanOptions;
}
}Usage Examples:
clean: {
build: {
src: ['tmp/'],
options: {
'no-write': true // Dry run
}
},
dangerous: {
src: ['../outside-project/'],
options: {
force: true // Allow deletion outside CWD
}
}
}Options that can be applied to all clean targets or specified per-target.
interface CleanOptions {
/** Override protection against deleting files outside current working directory */
force?: boolean;
/** Dry-run mode - logs what would be deleted without actually deleting */
'no-write'?: boolean;
}Overrides the default protection against deleting files outside the current working directory.
// Global options for all targets
clean: {
options: {
force: boolean // Default: false or grunt.option('force')
},
// targets...
}Usage Examples:
// Enable force globally (dangerous!)
clean: {
options: {
force: true
},
project: ['../other-project/build/']
}
// Enable force per-target
clean: {
local: ['tmp/'],
external: {
src: ['../shared-cache/'],
options: { force: true }
}
}Enables dry-run mode where the task logs what would be deleted without actually performing deletions.
// Global or per-target option
'no-write': boolean // Default: false or grunt.option('no-write')Usage Examples:
// Global dry-run
clean: {
options: {
'no-write': true
},
build: ['tmp/', 'dist/']
}
// Per-target dry-run
clean: {
build: ['tmp/'],
test: {
src: ['dist/'],
options: { 'no-write': true }
}
}Supports standard glob patterns for flexible file selection.
// Glob pattern examples
clean: {
// Delete entire folder
folder: ['path/to/dir/'],
folder_alt: ['path/to/dir/**'],
// Delete folder contents but keep folder
contents: ['path/to/dir/*'],
// Delete only subfolders
subfolders: ['path/to/dir/*/'],
// Delete specific file types
css: ['path/to/dir/*.css'],
all_css: ['path/to/dir/**/*.css'],
// Exclude patterns (use ! prefix)
js_except_min: ['path/to/dir/*.js', '!path/to/dir/*.min.js']
}The plugin includes multiple safety mechanisms to prevent accidental data loss.
Prevents deletion of the current working directory unless explicitly overridden.
// These operations are blocked by default:
clean: ['./', process.cwd()]
// Override with force option:
clean: {
options: { force: true },
dangerous: ['./']
}Prevents deletion of files outside the current working directory unless explicitly overridden.
// These operations are blocked by default:
clean: ['../other-project/', '/absolute/path/']
// Override with force option:
clean: {
options: { force: true },
external: ['../shared-build/']
}Automatically checks if files exist before attempting deletion to avoid errors.
The clean task supports various command line execution patterns and options.
// Command execution patterns
grunt clean // Run all clean targets
grunt clean:targetName // Run specific target
grunt clean --option-name // Run with command line optionsUsage Examples:
# Run all configured clean targets
grunt clean
# Run specific clean target
grunt clean:build
grunt clean:release
# Combine with other tasks
grunt build clean:build testOptions can be passed via command line flags to override configuration.
// Command line option integration
grunt clean --no-write // Enable dry-run mode
grunt clean --force // Enable force mode
grunt clean --verbose // Enable verbose loggingUsage Examples:
# Dry-run mode - show what would be deleted
grunt clean --no-write
# Force mode - allow deletion outside CWD (dangerous!)
grunt clean --force
# Verbose logging - show detailed operation info
grunt clean --verbose
# Combine options
grunt clean:build --no-write --verboseThe plugin provides comprehensive error handling with detailed error messages and graceful failure modes.
// Error handling patterns and responses
interface ErrorHandling {
fileNotExists: "skip_silently"; // No error, continues processing
permissionDenied: "fail_with_error"; // grunt.fail.warn() with details
cwdProtection: "fail_with_warning"; // grunt.fail.warn() with safety message
outsideCwdProtection: "fail_with_warning"; // grunt.fail.warn() with safety message
rimrafError: "fail_with_details"; // grunt.fail.warn() with underlying error
}Error Categories:
Example Error Messages:
// Safety protection errors
"Cannot delete the current working directory."
"Cannot delete files outside the current working directory."
// Deletion errors
'Unable to delete "path/to/file" file (EACCES: permission denied).'Error Recovery:
async.eachSeriesProvides detailed logging information about cleanup operations.
// Logging features:
// - Verbose mode shows each file being cleaned
// - Dry-run mode shows what would be cleaned
// - Success messages show total paths cleaned
// - Error messages include file paths and error detailsExample Output:
Running "clean:build" (clean) task
Cleaning tmp/file1.js...
Cleaning tmp/file2.js...
Cleaning dist/old.css...
>> 3 paths cleaned.
Done.Internal function that handles individual file/directory deletion with safety checks.
/**
* Internal function that handles individual file/directory deletion
* @param {string} filepath - Path to file or directory to delete
* @param {CleanOptions} options - Configuration options (force, no-write)
* @param {Function} done - Callback function called when operation completes
*/
function clean(filepath, options, done) {
// Safety checks:
// - Check if file exists (skip if doesn't exist)
// - Prevent CWD deletion unless force=true
// - Prevent outside-CWD deletion unless force=true
//
// Deletion:
// - Log operation (verbose mode)
// - Skip actual deletion if no-write=true
// - Use rimraf for actual deletion
// - Call done() callback with any errors
}Implementation Details:
done() if file doesn't exist (no error)options.force is trueoptions.force is trueoptions['no-write'] is truerimraf library for cross-platform recursive deletiondone(error) callback with any deletion errors// Short format
type CleanConfigShort = string[];
// Medium format
type CleanConfigMedium = {
[targetName: string]: string[];
};
// Long format
type CleanConfigLong = {
options?: CleanOptions;
[targetName: string]: {
src: string[];
options?: CleanOptions;
};
};
// Combined configuration type
type CleanConfig = CleanConfigShort | CleanConfigMedium | CleanConfigLong;interface CleanOptions {
/**
* Override protection against deleting files outside current working directory
* Default: false or grunt.option('force')
*/
force?: boolean;
/**
* Dry-run mode - logs what would be deleted without actually deleting
* Default: false or grunt.option('no-write')
*/
'no-write'?: boolean;
}