All files / libs/fs exists.js

100% Statements 14/14
100% Branches 5/5
100% Functions 4/4
100% Lines 13/13
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74                1x                                                                   1x 97x   97x 97x 37x 41x 41x     60x                 1x 1x               1x 1x    
/**
 * @module      libs/fs/exists
 * @createdAt   2016-06-30
 *
 * @copyright   Copyright (c) 2016 Zhonglei Qiu
 * @license     Licensed under the MIT license.
 */
 
var fs = require('fs')
 
/**
 *
 * 以同步的方式判断文件是否存在
 *
 * 支持指定允许的文件类型,默认只会判断 stat.isFile,
 * 通过第二个参数可以指定文件类型,可以设置成单个,
 * 或多个类型;如果指定了多个类型,则只要有一个成功
 * 就会返回 true
 *
 * @param     {String}               filepath    文件路径
 * @param     {String|Array<String>} [allowTypes]  允许的文件类型,支持下面几种:
 *   - File
 *   - Directory
 *   - BlockDevice
 *   - CharacterDevice
 *   - FIFO
 *   - Socket
 *
 * @return    {Boolean}
 *
 * @example
 *
 * exists('./some/path')                         // 判断是否是文件
 * exists('./some/path', 'File')                 // 判断是否是文件
 * exists('./some/path', 'Directory')            // 判断是否是文件夹
 * exists('./some/path', ['File', 'Directory'])  // 判断是文件或者文件侠,返回 false/'file'/'directory'
 *
 *
 * @author    Zhongle Qiu
 * @since     2.0.0
 *
 */
module.exports = function(filepath, allowTypes) {
  if (!allowTypes) allowTypes = 'File'
 
  try {
    var stats = fs.statSync(filepath)
    return [].concat(allowTypes).some(function(type) {
      var typeFn = 'is' + type[0].toUpperCase() + type.slice(1)
      return stats[typeFn] && stats[typeFn]() && type
    })
  } catch (e) {
    return false
  }
}
 
/**
 * 文件是否存在
 * @param  {String} file 文件路径
 * @return {Boolean}
 */
module.exports.file = function(file) {
  return module.exports(file, 'File')
}
 
/**
 * 目录是否存在
 * @param  {String} dir 目录路径
 * @return {Boolean}
 */
module.exports.directory = function(dir) {
  return module.exports(dir, 'Directory')
}