DailyJS

Trash: Cross-Platform Delete

Alex R. Young

Subscribe

@dailyjs

Facebook

Google+

cli node modules npm

Trash: Cross-Platform Delete

Posted by Alex R. Young on .
Featured

cli node modules npm

Trash: Cross-Platform Delete

Posted by Alex R. Young on .

Trash

Trash (GitHub: sindresorhus / trash, License: MIT, npm: trash) is a cross-platform command-line tool for safely deleting files.

Although those of us who are raised on Linux find the indignity of a Trash folder or Recycle Bin annoying, it can be a useful safety net. It has support for Windows, OS X, and Linux:

function win(paths, cb) {  
  execFile('./Recycle.exe', ['-f'].concat(paths), {
    cwd: path.join(__dirname, 'vendor', 'cmdutils')
  }, function (err) {
    cb(err);
  });
}

The Linux version has a small script that wraps around trash-cli:

function linux(paths, cb) {  
  execFile('./trash-put', paths, {
    cwd: path.join(__dirname, 'vendor')
  }, function (err) {
    if (err && /cannot trash non existent/.test(err.message)) {
      return cb(new Error('Item doesn\'t exist'));
    }

    cb(err);
  });
}

The test is written as an integration test, so it uses Node's fs module to create and move files:

it('should trash files', function (cb) {  
  fs.writeFileSync('fixture', '');
  fs.writeFileSync('fixture2', '');
  fs.writeFileSync('weird\\\\name\\"\'', '');
  assert(fs.existsSync('fixture'));
  assert(fs.existsSync('fixture2'));
  assert(fs.existsSync('weird\\\\name\\"\''));

  trash([
    'fixture',
    'fixture2',
    'weird\\\\name\\"\''
  ], function (err) {
    assert(!err, err);
    assert(!fs.existsSync('fixture'));
    assert(!fs.existsSync('fixture2'));
    assert(!fs.existsSync('weird\\\\name\\"\''));
    cb();
  });
});