/
path.ts
64 lines (60 loc) · 1.77 KB
/
path.ts
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
import { dirname as dir, basename as base, extname as ext, join, normalize } from 'path';
/**
* @description
* Get full path to file or its directory name
* @param filepath - Path
* @param full - Get full path or file directory name only?
* @example
* ```ts
* import { path } from '@biorate/tools';
* console.log(path.dirname('/www/root/index.html')); // root
* console.log(path.dirname('/www/root/index.html', true)); // /www/root
* ```
*/
export function dirname(filepath: string, full = false) {
return !full ? dir(filepath).split('/').pop() : dir(filepath);
}
/**
* @description
* Get file basename, with .js ext by default
* @param filepath - Path
* @param ext - extname of file
* @example
* ```ts
* import { path } from '@biorate/tools';
* console.log(path.basename('/www/root/index.js', '.js')); // index
* console.log(path.basename('/www/root/index.js', '')); // index.js
* console.log(path.basename('/www/root/index.html', '.html')); // index
* console.log(path.basename('/www/root/index.html')); // index.html
* ```
*/
export function basename(filepath: string, ext = '.js') {
return base(filepath, ext);
}
/**
* @description
* Get file extname
* @param filepath - Path
* @example
* ```ts
* import { path } from '@biorate/tools';
* console.log(path.extname('/www/root/index.js')); // .js
* console.log(path.extname('/www/root/index.html')); // .html
* ```
*/
export function extname(filepath: string) {
return ext(basename(filepath, ''));
}
/**
* @description
* Create normalized path from strings
* @example
* ```ts
* import { path } from '@biorate/tools';
* console.log(path.create('www', 'root/a/b/', '/c/', '', '/index.js'));
* // www/root/a/b/c/index.js
* ```
*/
export function create(...args: string[]) {
return normalize(join(...args));
}