UNPKG

1.62 kBJavaScriptView Raw
1/**
2 * Delete file.
3 * @function filedel
4 * @param {string} filename - Filename to delete.
5 * @param {object} [options] - Optional settings.
6 * @param {boolean} [options.force=false] - Unlink even if readonly.
7 * @returns {Promise}
8 */
9
10'use strict'
11
12const rimraf = require('rimraf')
13const {existsAsync} = require('asfs')
14const argx = require('argx')
15const aglob = require('aglob')
16const doUnlink = require('./filing/do_unlink')
17const isDir = require('./filing/is_dir')
18
19/** @lends filedel */
20async function filedel (patterns, options = {}) {
21 const args = argx(arguments)
22 if (args.pop('function')) {
23 throw new Error('[filedel] Callback is no more supported. Use promise interface instead.')
24 }
25 const {cwd = process.cwd()} = options
26 options = args.pop('object') || {}
27
28 const filenames = await aglob(patterns, {cwd})
29 const result = []
30 for (const filename of filenames) {
31 const exists = await existsAsync(filename)
32 if (!exists) {
33 return
34 }
35 const isDir_ = await isDir(filename)
36 if (isDir_) {
37 throw new Error(`[filedel] Can not unlink directory: ${filename}`)
38 }
39 await doUnlink(filename, Boolean(options.force))
40 result.push(filename)
41 }
42 return result
43}
44
45Object.assign(filedel, {
46 async recursive (dirname) {
47 const exists = await existsAsync(dirname)
48 if (!exists) {
49 return
50 }
51 const isDir_ = await isDir(dirname)
52 if (!isDir_) {
53 throw new Error(`[filedel] Not a directory: ${dirname}`)
54 }
55 await new Promise((resolve, reject) =>
56 rimraf(dirname, (err) => err ? reject(err) : resolve())
57 )
58 }
59})
60
61module.exports = filedel