Convert Figma logo to code with AI

sindresorhus logodel

Delete files and directories

1,318
65
1,318
19

Top Related Projects

5,609

A `rm -rf` util for nodejs

Node.js: extra methods for the fs object like copy(), remove(), mkdirs()

glob functionality for node.js

Quick Overview

Del is a Node.js package that provides a convenient way to delete files and directories. It offers a promise-based API for deleting files and directories, with support for globbing patterns and various options to control the deletion process.

Pros

  • Simple and intuitive API for deleting files and directories
  • Supports globbing patterns for flexible file selection
  • Provides options for force deletion, dry runs, and preserving root directories
  • Well-maintained and actively developed

Cons

  • Limited to Node.js environments
  • May require additional configuration for complex deletion scenarios
  • Potential for accidental data loss if used incorrectly
  • Lacks some advanced features found in more specialized file management libraries

Code Examples

Deleting files in a directory:

import del from 'del';

await del(['temp/*.js', '!temp/important.js']);
console.log('Temporary JavaScript files deleted');

Deleting directories with force option:

import del from 'del';

const deletedPaths = await del(['old-project'], { force: true });
console.log('Deleted files and directories:\n', deletedPaths.join('\n'));

Dry run to preview files that would be deleted:

import del from 'del';

const deletedPaths = await del(['dist/**'], { dryRun: true });
console.log('Files that would be deleted:\n', deletedPaths.join('\n'));

Getting Started

To use Del in your Node.js project, follow these steps:

  1. Install the package:

    npm install del
    
  2. Import and use in your JavaScript file:

    import del from 'del';
    
    async function cleanUp() {
      try {
        const paths = await del(['build', 'temp/**', '!temp/important.txt']);
        console.log('Deleted files and directories:\n', paths.join('\n'));
      } catch (error) {
        console.error('Error during cleanup:', error);
      }
    }
    
    cleanUp();
    

This example demonstrates how to delete the 'build' directory and all files in the 'temp' directory except for 'important.txt'. Adjust the patterns and options as needed for your specific use case.

Competitor Comparisons

5,609

A `rm -rf` util for nodejs

Pros of rimraf

  • More mature and widely used project with a longer history
  • Supports synchronous operation in addition to asynchronous
  • Provides a command-line interface for easy use in scripts

Cons of rimraf

  • Less actively maintained compared to del
  • Doesn't support globbing patterns out of the box (requires glob package)
  • Lacks some advanced features like dry run and cleaning outside working directory

Code Comparison

rimraf:

const rimraf = require('rimraf');
rimraf('/path/to/directory', (err) => {
  if (err) console.error(err);
});

del:

const del = require('del');
(async () => {
  try {
    await del(['/path/to/directory']);
  } catch (err) {
    console.error(err);
  }
})();

Both rimraf and del are popular Node.js packages for deleting files and directories. rimraf is older and more established, while del offers more modern features and better globbing support. rimraf provides both sync and async operations, whereas del focuses on Promise-based async operations. del has a more active development cycle and includes additional features like dry run and cleaning outside the working directory. The choice between the two depends on specific project requirements and preferences for API style.

Node.js: extra methods for the fs object like copy(), remove(), mkdirs()

Pros of node-fs-extra

  • Provides a more comprehensive set of file system operations
  • Offers both synchronous and asynchronous versions of methods
  • Includes additional utility functions like emptyDir and outputFile

Cons of node-fs-extra

  • Larger package size due to more extensive functionality
  • May have a steeper learning curve for beginners
  • Not specifically optimized for deletion operations like del

Code Comparison

node-fs-extra:

const fs = require('fs-extra');

fs.remove('/path/to/file', err => {
  if (err) return console.error(err);
  console.log('File removed successfully');
});

del:

const del = require('del');

(async () => {
    const deletedPaths = await del(['/path/to/file']);
    console.log('Deleted files and directories:\n', deletedPaths.join('\n'));
})();

Summary

node-fs-extra is a more comprehensive file system manipulation library, offering a wide range of operations beyond deletion. It's suitable for projects requiring extensive file system interactions. del, on the other hand, is a specialized tool focused on efficient file and directory deletion, with a simpler API and smaller package size. The choice between the two depends on the specific needs of your project and the scope of file system operations required.

glob functionality for node.js

Pros of node-glob

  • More comprehensive globbing functionality, supporting advanced patterns
  • Widely used and battle-tested in many popular projects
  • Provides both sync and async APIs for flexibility

Cons of node-glob

  • Larger package size and potentially slower performance
  • More complex API, which may be overkill for simple use cases
  • Requires more setup and configuration for basic file deletion tasks

Code Comparison

node-glob:

const glob = require('glob');

glob('**/*.js', (err, files) => {
  if (err) throw err;
  console.log(files);
});

del:

const del = require('del');

(async () => {
  const deletedPaths = await del(['**/*.js']);
  console.log('Deleted files and directories:\n', deletedPaths.join('\n'));
})();

Summary

node-glob is a powerful and flexible globbing library, offering advanced pattern matching and both sync and async APIs. It's well-suited for complex file searching tasks but may be overkill for simple operations. del, on the other hand, is more focused on file and directory deletion, providing a simpler API and better performance for these specific tasks. While node-glob offers more comprehensive globbing functionality, del excels in ease of use and efficiency for deletion operations. The choice between the two depends on the specific requirements of your project and the complexity of the file operations you need to perform.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

del

Delete files and directories using globs

Similar to rimraf, but with a Promise API and support for multiple files and globbing. It also protects you against deleting the current working directory and above.

Install

npm install del

Usage

import {deleteAsync} from 'del';

const deletedFilePaths = await deleteAsync(['temp/*.js', '!temp/unicorn.js']);
const deletedDirectoryPaths = await deleteAsync(['temp', 'public']);

console.log('Deleted files:\n', deletedFilePaths.join('\n'));
console.log('\n\n');
console.log('Deleted directories:\n', deletedDirectoryPaths.join('\n'));

Beware

The glob pattern ** matches all children and the parent.

So this won't work:

deleteSync(['public/assets/**', '!public/assets/goat.png']);

You have to explicitly ignore the parent directories too:

deleteSync(['public/assets/**', '!public/assets', '!public/assets/goat.png']);

To delete all subdirectories inside public/, you can do:

deleteSync(['public/*/']);

Suggestions on how to improve this welcome!

API

Note that glob patterns can only contain forward-slashes, not backward-slashes. Windows file paths can use backward-slashes as long as the path does not contain any glob-like characters, otherwise use path.posix.join() instead of path.join().

deleteAsync(patterns, options?)

Returns Promise<string[]> with the deleted paths.

deleteSync(patterns, options?)

Returns string[] with the deleted paths.

patterns

Type: string | string[]

See the supported glob patterns.

options

Type: object

You can specify any of the globby options in addition to the below options. In contrast to the globby defaults, expandDirectories, onlyFiles, and followSymbolicLinks are false by default.

force

Type: boolean
Default: false

Allow deleting the current working directory and outside.

dryRun

Type: boolean
Default: false

See what would be deleted.

import {deleteAsync} from 'del';

const deletedPaths = await deleteAsync(['temp/*.js'], {dryRun: true});

console.log('Files and directories that would be deleted:\n', deletedPaths.join('\n'));
dot

Type: boolean
Default: false

Allow patterns to match files/folders that start with a period (.).

This option is passed through to fast-glob.

Note that an explicit dot in a portion of the pattern will always match dot files.

Example

directory/
├── .editorconfig
└── package.json
import {deleteSync} from 'del';

deleteSync('*', {dot: false});
//=> ['package.json']
deleteSync('*', {dot: true});
//=> ['.editorconfig', 'package.json']
concurrency

Type: number
Default: Infinity
Minimum: 1

Concurrency limit.

onProgress

Type: (progress: ProgressData) => void

Called after each file or directory is deleted.

import {deleteAsync} from 'del';

await deleteAsync(patterns, {
	onProgress: progress => {
	// …
}});
ProgressData
{
	totalCount: number,
	deletedCount: number,
	percent: number,
	path?: string
}
  • percent is a value between 0 and 1
  • path is the absolute path of the deleted file or directory. It will not be present if nothing was deleted.

CLI

See del-cli for a CLI for this module and trash-cli for a safe version that is suitable for running by hand.

del for enterprise

Available as part of the Tidelift Subscription.

The maintainers of del and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.

Related

  • make-dir - Make a directory and its parents if needed
  • globby - User-friendly glob matching

NPM DownloadsLast 30 Days