UNPKG

1.42 kBJavaScriptView Raw
1const FS = require('fs');
2const Util = require('util');
3const mkdirp = require('make-dir');
4const Path = require('path');
5
6const 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
15FS2.hasAccess = (path, mode) => FS2.access(path, mode)
16 .then(
17 () => true,
18 err => {
19 // if file does not exist or permission is denied, return false, otherwise throw
20 if(err.code === 'ENOENT' || err.code === 'EACCES') {
21 return false;
22 }
23 throw err;
24 }
25 );
26
27FS2.exists = path => FS2.hasAccess(path, FS2.constants.F_OK);
28
29FS2.readText = path => FS2.readFile(path, {encoding: 'utf8'});
30
31FS2.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
43FS2.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
52module.exports = FS2;
\No newline at end of file