1 |
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | 'use strict'
|
11 |
|
12 | const rimraf = require('rimraf')
|
13 | const {existsAsync} = require('asfs')
|
14 | const argx = require('argx')
|
15 | const aglob = require('aglob')
|
16 | const doUnlink = require('./filing/do_unlink')
|
17 | const isDir = require('./filing/is_dir')
|
18 |
|
19 |
|
20 | async 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 |
|
45 | Object.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 |
|
61 | module.exports = filedel
|