Move files and directories to the trash

Overview

trash

Move files and folders to the trash

Works on macOS (10.12+), Linux, and Windows (8+).

Note: The Linux implementation is not very good and not maintained. Help welcome. If no one steps up to help maintain it, I will eventually remove Linux support.

In contrast to fs.unlink, del, and rimraf which permanently delete files, this only moves them to the trash, which is much safer and reversible.

Install

$ npm install trash

Usage

const trash = require('trash');

(async () => {
	await trash(['*.png', '!rainbow.png']);
})();

API

trash(input, options?)

Returns a Promise.

input

Type: string | string[]

Accepts paths and glob patterns.

options

Type: object

glob

Type: boolean
Default: true

Enable globbing when matching file paths.

CLI

To install the trash command, run:

$ npm install --global trash-cli

Info

On macOS, macos-trash is used.
On Linux, the XDG spec is followed.
On Windows, recycle-bin is used.

FAQ

But I can do the same thing with mv

Not really. The mv command isn't cross-platform and moving to trash is not just about moving the file to a "trash" directory. On all OSes you'll run into file conflicts. The user won't easily be able to restore the file. It won't work on an external drive. The trash directory location varies between Windows versions. For Linux, there's a whole spec you need to follow. On macOS, you'll lose the Put back feature.

Related

Comments
  • Trashing a file on Ubuntu Linux deletes it unrecoverably

    Trashing a file on Ubuntu Linux deletes it unrecoverably

    Issuehunt badges

    On Ubuntu 16.10, when I use the command-line tool trash to delete a file, rather than a folder, the file is deleted immediately rather than appearing in the Trash where I can recover it. In other words, trash acts like rm -f when given a file.

    Some commands that demonstrate the problem:

    $ pwd
    /home/roryokane
    
    $ # delete files
    
    $ touch aaaaaa.txt
    $ trash aaaaaa.txt
    
    $ touch bbbbbb.txt
    $ echo "contents of bbbbbb" > bbbbbb.txt
    $ trash bbbbbb.txt
    
    $ # delete folders
    
    $ mkdir cccccc
    $ touch cccccc/foo.txt
    $ echo "contents of foo" > cccccc/foo.txt
    $ trash cccccc
    
    $ mkdir dddddd
    $ trash dddddd
    

    When I look in my Trash by clicking the Trash icon in the dock/taskbar, I only see the cccccc and dddddd folders in the trash. The aaaaaa.txt and bbbbbb.txt files are missing.

    Trash showing only ‘cccccc’ and ‘dddddd’

    My environment

    I used the xdg-trashdir package, which trash currently uses, to find the location of my Trash directories. Here is my Node session:

    const xdgTrashdir = require('xdg-trashdir');
    let dirs = []
    xdgTrashdir.all().then(dirsInner => dirs = dirsInner)
    dirs.forEach(dir => console.log(dir))
    

    And the output:

    /dev/.Trash-1000
    /run/.Trash-1000
    /home/roryokane/.local/share/Trash
    /dev/shm/.Trash-1000
    /run/lock/.Trash-1000
    /sys/fs/cgroup/.Trash-1000
    /snap/core/1337/.Trash-1000
    /snap/keepassx-elopio/1/.Trash-1000
    /snap/core/1287/.Trash-1000
    /snap/core/1264/.Trash-1000
    /home/roryokane/.local/share/Trash
    /run/user/1000/.Trash-1000
    

    Saving that to a file and running cat trash_dirs.txt | xargs ls showed that the only folder of those that exists is /home/roryokane/.local/share/Trash, which contains expunged/, files/, and info/. None of those folders contain files or folders with aaaaaa, bbbbbb, cccccc, or dddddd in their names. Also, when I search for those four files and folders using the Files program to search those names from the root of the disk, none of them are found.

    I installed trash with Yarn:

    $ which trash
    /home/roryokane/.yarn-global/bin/trash
    $ yarn global ls
    yarn global v0.21.3
    warning No license field
    info "[email protected]" has binaries:
       - gitjk_cmd
       - git-jk
    info "[email protected]" has binaries:
       - trash
    Done in 0.61s.
    

    IssueHunt Summary

    gsittyz gsittyz has been rewarded.

    Backers (Total: $60.00)

    Submitted pull Requests


    Tips

    bug help wanted :gift: Rewarded on Issuehunt 
    opened by roryokane 16
  • Improve performance on Linux

    Improve performance on Linux

    Issuehunt badges

    $ sed -e '/^+.*/p' a > b
    $ time rm b
    
    real    0m0.361s
    user    0m0.161s
    sys     0m0.027s
    $ sed -e '/^+.*/p' a > b
    $ time \rm b
    
    real    0m0.002s
    user    0m0.000s
    sys     0m0.002s
    $ type rm
    rm is aliased to trash
    
    $ ls -a -l
    -rw-rw-r--  1 nikhil 179K Jan 25 11:27 b
    

    IssueHunt Summary

    stroncium stroncium has been rewarded.

    Backers (Total: $80.00)

    Submitted pull Requests


    Tips


    IssueHunt has been backed by the following sponsors. Become a sponsor

    enhancement help wanted :gift: Rewarded on Issuehunt 
    opened by lamyergeier 14
  • Trash not working after 3.0.0 Update (Win7)

    Trash not working after 3.0.0 Update (Win7)

    After updating to v 3.1.1 (Win7), trash is no longer working. Before the update it worked perfect when I had v2.0.0.

    I get the following when trying to trash anything now.

    sh.exe": /local/trash: No such file or directory
    
    opened by mscarchilli 12
  • linux: fix to comply with XDG, and show correct name in GNOME Trash

    linux: fix to comply with XDG, and show correct name in GNOME Trash

    When trashing a file or directory, the implementation MUST create the corresponding file in $trash/info first. Moreover, it MUST try to do this in an atomic fashion, so that if two processes try to trash files with the same filename this will result in two different trash files. On Unix-line systems this is done by generating a filename, and then opening with O_EXCL.

    https://specifications.freedesktop.org/trash-spec/trashspec-latest.html

    It looks like GnomeVFS was sanity-checking the timestamps. So if you break the rule and don't create the trashinfo file first, then GnomeVFS will ignore it :-).

    Fixes #56

    opened by sourcejedi 8
  • zsh: command not found: trash

    zsh: command not found: trash

    I just installed trash and I'm using ZSH. I get zsh: command not found: trash error.

    $ trash a.txt
    zsh: command not found: trash
    
    $ npm list --depth=0
    /Users/zulhilmizainudin
    ├── [email protected]
    └── [email protected]
    
    $ npm -v
    2.6.1
    

    What should I do?

    opened by zulhfreelancer 7
  • Not working on linux systems where python defaults to python3

    Not working on linux systems where python defaults to python3

    $ touch test
    $ trash test
    Command failed: Traceback (most recent call last):
      File "./trash-put", line 4, in <module>
        from trashcli.put import main
      File "/home/despairblue/node_modules/trash/vendor/trash-cli/trashcli/put.py", line 255
        except (IOError, OSError), error:
                                 ^
    SyntaxError: invalid syntax
    
    opened by despairblue 7
  • Accept a string

    Accept a string

    Like globby, I assumed this module accepted a string. When I passed in '/foo/bar/car' it turned it into an array of ['/', 'f', 'o', ...] and globbed a result of of

    ['/', '/foo/bar/car']
    

    The value of / was not what I wanted :warning:. In earlier versions trash would have thrown an error if it received a string. However, now it silently accepts a string and happily trashes root.

    The nas I'm on has limited storage on root so the trash fills up fast with no-space errors. It also let's me muck with / without borking, restoring off another partition, so no worries.

    opened by jdalton 6
  • Move files to the proper Trash

    Move files to the proper Trash

    The command:

    trash /Volumes/something/abc
    

    moves the file/directory to ~/.Trash on OS X, i.e. moves it to a different drive. It should just move the file/directory to the trash proper for the volume the file is on.

    Tested on OS X Yosemite with trash 1.2.0.

    opened by mgol 6
  • Use xdg-trash for Linux

    Use xdg-trash for Linux

    Only node required you say? I say yes! Although it could be worth waiting for support for external drives before merging. It's not a requirement in the trash spec (only MAY use) so it wouldn't be wrong to merge either.

    opened by kevva 6
  • Linux XDG Trash node module

    Linux XDG Trash node module

    Currently I'm using trash-cli which works fine, but it's Python dependent and slow as it's excuted in a child process.

    There's a spec on how to implement "moving files to the trash" correctly.

    It would be incredible if someone would be interested in writing a separate node module for this.

    Let me know if you're interested ;)

    enhancement help wanted 
    opened by sindresorhus 6
  • fs.lstatSync throws when file doesn't exist.

    fs.lstatSync throws when file doesn't exist.

    With the addition of using fs.lstatSync https://github.com/sindresorhus/trash/commit/126a1dd1532d0bdd236628fb8db505db033d9273, now trash errors with

    Error: ENOENT: no such file or directory, lstat './the-file'
       at Object.fs.lstatSync 
    

    When a file doesn't exist, where as fs.existsSync would return false.

    Related to #64 (\cc @jdanford)

    opened by jdalton 5
  • Trashing a file on Windows deletes it unrecoverably if no recycle bin is enabled

    Trashing a file on Windows deletes it unrecoverably if no recycle bin is enabled

    Similar to #56, but probably has to be solved in a different way for Windows. This was reported by a user in my app losslesscut https://github.com/mifi/lossless-cut/issues/537 When he trashed a file on a network mounted drive (which has no trash), the file just got removed permanently.

    bug help wanted 
    opened by mifi 5
  • Trouble deteting some files

    Trouble deteting some files

    trash wasn't able to delete a file named \ \ ㊕\ 八倍縮時影片⏩\ 📺\ 🚲🚴\ 8\ ✖\ Time\ lapse\ _\ 上水\ Sheung\ Shui\ ⬄\ 粉嶺\ Fanling\ _\ 2020-Oct-28\ -FxRsQ-yrtG4.webm but rm did

    bug help wanted 
    opened by chapmanjacobd 3
  • Confusion for Windows + WSL

    Confusion for Windows + WSL

    I have windows 10 + WSL (v1). I just installed this tool and tried to use it on a file inside WSL... I was expecting it to move the file to my Recycle Bin. It didn't work, but then I realized it put the file (renamed) inside ~/.local/share/Trash/files/ (according to that linux spec I guess).

    I now realize this wasn't going to work like I expected since the tool is running in a linux environment (WSL), not actual windows.

    I'm not sure if there's any way to get this tool installed out in windows land and still be able to run it from inside WSL to do what I expected, but if that's possible it would be nice to add something about that to the documentation.

    Alternately and minimally, it might be a good idea to point in the docs out that installing under WSL in Windows is actually installing in linux, and pointing out where deleted files will go. Could remove some future confusion I had for the last ~20 minutes.

    enhancement help wanted 
    opened by getify 2
  • Doesn't find correct Trash folder on NixOS

    Doesn't find correct Trash folder on NixOS

    I've been trying to use trash via coc-explorer, but it doesn't seem to find the the correct Trash folder. I've investigated xdgTrashdir a bit to see if it was the cause, but xdgTrashdir() with no arguments seems to find my home trash dir fine (/home/$USER/.local/share/Trash).

    The issue here is that according to trash my Trash folder is supposed to be /nix/store/.Trash-1000, which is not correct. NixOS uses a weird filesystem, and I'm not too familiar with why this is happening, but my best guess is that the mount mapping logic finds /nix/store as the mount the target directory $topdir according to the spec.

    This is not the expected behavior, as /nix/store resides on the same filesystem and mount that my home folder does. I'm not familiar with how the mount points are resolved, so I'm not sure exactly how to fix this, but I'd gladly help with anything else I can do.

    bug help wanted 
    opened by johnpyp 0
  • How to tell whether deletion succeeded?

    How to tell whether deletion succeeded?

    README claims trash() returns a Promise, but the expected type is void? https://github.com/sindresorhus/trash/blob/bdfbd071e491df63c2e59bb4d72ebfac6c60ef10/index.test-d.ts#L4

    So there is currently no way to tell whether the library succeeded in moving a file into the trash or whether it encountered an error?

    trash('some-file.lol')
      .then((result) => {
        console.log(result); // always `undefined`
      })
      .catch((err) => {
        console.log(err); // never runs
      });
    

    So, the library just sends a command to the OS and doesn't know what happens after?

    When you tell the library to delete a non-existing file, it behaves the same way (no error, no notification).

    This isn't a problem -- it's just that I'd love to have my app respond appropriately, not just assume that deletion occurred correctly 😓

    I can manually get node to check whether the file is present to confirm it was deleted, but would be great if I didn't have to 😅

    Please let me know if I'm misunderstanding something.

    opened by whyboris 2
  • [linux] EISDIR: illegal operation on a directory

    [linux] EISDIR: illegal operation on a directory

    trash (invoked, in my case, via trash-cli) does not seem to work on directories in Linux (in my case, Ubuntu 19.10).

    $ trash {src,test,build}/**/*.{js,d.ts,map}
    Error: EISDIR: illegal operation on a directory, copyfile '/builds/build/es6' -> '/root/.local/share/Trash/files/c862ddbe-a1f8-4589-b545-fe260f81e2e9'
    
    bug help wanted 
    opened by haggholm 5
Releases(v8.1.0)
  • v8.1.0(Dec 18, 2021)

  • v8.0.0(Oct 1, 2021)

  • v7.2.0(Jun 13, 2021)

  • v7.1.1(Mar 8, 2021)

  • v7.1.0(Jan 27, 2021)

  • v7.0.0(Nov 20, 2020)

  • v6.1.1(Nov 19, 2019)

  • v6.1.0(Nov 17, 2019)

  • v6.0.0(May 29, 2019)

    Breaking;

    • Drop support for macOS 10.11 and older cc399fe
    • Drop support for Windows 7 and older 8ec3260

    Enhancements:

    • Support long paths on Windows 8ec3260

    https://github.com/sindresorhus/trash/compare/v5.2.0...v6.0.0

    Source code(tar.gz)
    Source code(zip)
  • v5.2.0(Apr 1, 2019)

  • v5.1.0(Mar 31, 2019)

  • v5.0.0(Mar 8, 2019)

    Breaking:

    • Drop support for Iterable as input, use string | string[] aa29749
    • Require Node.js 8 6cd7609

    Enhancements:

    • Add TypeScript definition (#81) c029c43

    https://github.com/sindresorhus/trash/compare/v4.3.0...v5.0.0

    Source code(tar.gz)
    Source code(zip)
  • v3.0.0(Oct 22, 2015)

    The command-line tool was extracted into a separate module called trash-cli. (https://github.com/sindresorhus/trash/commit/bb137049c992deab5eef388e08f40c93787dd3a1) (Note that it now requires Node.js 4. Make sure to upgrade your Node.js install)

    Run this to migrate to the new CLI tool package:

    $ npm uninstall --global trash && npm install --global trash-cli
    

    You still use it as $ trash.

    Source code(tar.gz)
    Source code(zip)
  • v2.0.0(Aug 3, 2015)

    We decided to change trash to not error on missing files. It was only in the way and made it harder to use trash in scripts. The --force flag was also removed as it's pretty moot now. #29 #26

    https://github.com/sindresorhus/trash/compare/v1.4.1...v2.0.0

    Source code(tar.gz)
    Source code(zip)
  • v1.4.0(Jan 26, 2015)

  • v1.2.0(Oct 14, 2014)

Owner
Sindre Sorhus
Full-Time Open-Sourcerer. Wants more empathy & kindness in open source. Focuses on Swift & JavaScript. Makes macOS apps, CLI tools, npm packages. Likes unicorns
Sindre Sorhus
HMSC (How Much Stuffs CLI) analyst for your files and folders

HMSC ?? About HMSC (How Much Stuffs CLI) analyst for your files and folders ?? Screenshot ?? Requirements Node.js NPM ?? Installation $ npm i -g hmsc

Abdullah Veliyev 26 Jan 10, 2022
Run a command when a certain file exists, and/or watch files to rerun on changes

Run a command when a certain file exists, and/or watch files to rerun on changes

EGOIST 45 Sep 23, 2022
Copy files

cpy Copy files Why Fast by using streams. Resilient by using graceful-fs. User-friendly by accepting globs and creating non-existent destination direc

Sindre Sorhus 380 Nov 15, 2022
Windows command line tool to block outbound connections for files within a directory.

fwg A Windows command line tool to block outbound connections for files within a directory. fwg utilizes the power of PowerShell and Windows Network S

raymond wang 3 Jul 19, 2022
Started pack for working with the new GameTest Framework API. Usable in windows, and mobile in worlds and realms!

GameTest FrameWork GameTest FrameWork is a new feature in Minecraft Bedrock Edition. This gives you the ability to script! In this example I will be u

null 40 Dec 24, 2022
A CLI to add and remove local development environments and create HTTPS certificates for them.

A CLI used to create a local https dev environment with the green lock. Setup takes less than 5 minutes and all of your projects will be running locally over HTTPS with custom domain names in no time!

Entrostat (Pty) Ltd 5 Sep 19, 2022
Find and fix problems in your JavaScript code.

ESLint Website | Configuring | Rules | Contributing | Reporting Bugs | Code of Conduct | Twitter | Mailing List | Chat Room ESLint is a tool for ident

ESLint 22k Jan 8, 2023
Infinite Red's cutting edge React Native project boilerplate, along with a CLI, component/model generators, and more!

Ignite - the hottest React Native boilerplate Battle-tested React Native boilerplate The culmination of five years of constant React Native developmen

Infinite Red, Inc. 14.7k Dec 29, 2022
Test your internet connection speed and ping using speedtest.net from the CLI

speed-test Test your internet connection speed and ping using speedtest.net from the CLI Install Ensure you have Node.js version 8+ installed. Then ru

Sindre Sorhus 3.8k Jan 7, 2023
Detect copy-pasted and structurally similar code

Detect copy-pasted and structurally similar JavaScript code. Requires Node.js 6.0+, and supports ES6, JSX as well as Flow. Note: the project has been

Daniel St. Jules 3.5k Dec 26, 2022
Pipeable javascript. Quickly filter, map, and reduce from the terminal

Pipeable JavaScript - another utility like sed/awk/wc... but with JS! Quickly filter, map and reduce from the command line. Features a streaming API.

Daniel St. Jules 410 Dec 10, 2022
Kill all Chrome tabs to improve performance, decrease battery usage, and save memory

kill-tabs Kill all Chrome tabs to improve performance, decrease battery usage, and save memory Works on macOS, Linux, Windows. I'm a tab-abuser and I

Sindre Sorhus 371 Jan 8, 2023
📜 Create mutable log lines into the terminal, and give life to your logs!

Because Logging can be pretty and fun Installation $ npm install draftlog What it does It allows you to re-write a line of your log after being writt

Ivan Seidel 1.2k Dec 31, 2022
Add a hungry turtle to your terminal and feed it every time you mistype 'npm' as 'nom'

Nom Does this ever happen to you? You happily code away on a project, navigating the command line like a pro, testing, error logging, installing packa

Meike Hankewicz 5 Apr 26, 2022
replacement for comma.ai backend and useradmin dashboard. comes bundled with a modified cabana instance for seamless drive reviewing.

retropilot-server Replacement for comma.ai backend and useradmin dashboard. Bundled with a modified version of comma's cabana to allow viewing & analy

Florian Brede 39 Dec 4, 2022
Tasks Management CLI application with Nodejs, Mongodb, inquirer.js, and commander

Tasks CLI Tasks CLI is a program to manage your tasks in a database using terminal or console. This is a sample project for beginners Requirements Nod

Fazt Web 9 Nov 17, 2022
A simple CLI tool to create and manage xhelpers-api projects

A simple CLI tool to create and manage xhelpers-api projects

null 2 Feb 25, 2022
A fullstack(NestJS、React) framework for building efficient and scalable applications

A fullstack(NestJS、React) framework for building efficient and scalable applications. Description The Kunlun CLI is a command-line interface tool that

图灵人工智能研究院前端技术团队 3 Mar 12, 2022