1 | const FS = require('fs');
|
2 | const Util = require('util');
|
3 | const mkdirp = require('make-dir');
|
4 | const Path = require('path');
|
5 |
|
6 | const FS2 = Object.entries(FS).reduce((acc, [k, v]) => {
|
7 | if(typeof v === 'function' && /^[a-z]/.test(k) && !k.endsWith('Sync')) {
|
8 | acc[k] = Util.promisify(v);
|
9 | } else {
|
10 | acc[k] = v;
|
11 | }
|
12 | return acc;
|
13 | }, Object.create(null));
|
14 |
|
15 | FS2.hasAccess = (path, mode) => FS2.access(path, mode)
|
16 | .then(
|
17 | () => true,
|
18 | err => {
|
19 |
|
20 | if(err.code === 'ENOENT' || err.code === 'EACCES') {
|
21 | return false;
|
22 | }
|
23 | throw err;
|
24 | }
|
25 | );
|
26 |
|
27 | FS2.exists = path => FS2.hasAccess(path, FS2.constants.F_OK);
|
28 |
|
29 | FS2.readText = path => FS2.readFile(path, {encoding: 'utf8'});
|
30 |
|
31 | FS2.writeText = (path,contents) => {
|
32 | const write = () => FS2.writeFile(path, contents, {encoding: 'utf8'});
|
33 |
|
34 | return write().catch(async err => {
|
35 | if(err.code === 'ENOENT') {
|
36 | await mkdirp(Path.dirname(path));
|
37 | return write();
|
38 | }
|
39 | throw err;
|
40 | });
|
41 | };
|
42 |
|
43 | FS2.closest = async (filename, dir=process.cwd()) => {
|
44 | let path = Path.join(dir, filename);
|
45 | if(await FS2.exists(path)) {
|
46 | return path;
|
47 | }
|
48 | if(dir === '/') return null;
|
49 | return FS2.closest(filename, Path.dirname(dir));
|
50 | };
|
51 |
|
52 | module.exports = FS2; |
\ | No newline at end of file |