All files / libs/fs rm.js

100% Statements 14/14
100% Branches 3/3
100% Functions 4/4
100% Lines 14/14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                    2x 2x               13x 13x     1x 1x           12x 9x   3x         3x       9x 4x   9x     2x  
/**
 * 递归删除指定的文件夹或文件
 *
 * @module      libs/fs/rm
 * @createdAt   2016-08-05
 *
 * @copyright   Copyright (c) 2016 Zhonglei Qiu
 * @license     Licensed under the MIT license.
 */
 
var fs = require('fs')
var path = require('path')
 
/**
 * 递归遍历删除指定的文件或文件夹
 * @param  {String} file 要删除的文件的路径
 */
function rm(file) {
  var stat
  try {
    stat = fs.statSync(file)
  } catch (e) {
    /* istanbul ignore else */
    if (e.message.indexOf('ENOENT') === 0) {
      return false
    }
    /* istanbul ignore next */
    throw e
  }
 
  if (stat.isDirectory()) {
    return rmDir(file)
  } else {
    return rmFile(file)
  }
}
 
function rmFile(file) {
  return fs.unlinkSync(file)
}
 
function rmDir(dir) {
  fs.readdirSync(dir).forEach(function(item) {
    rm(path.join(dir, item))
  })
  return fs.rmdirSync(dir)
}
 
module.exports = rm