main
Last change
on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
1.3 KB
|
Rev | Line | |
---|
[d565449] | 1 | 'use strict';
|
---|
| 2 | const path = require('path');
|
---|
| 3 | const fs = require('fs');
|
---|
| 4 | const {promisify} = require('util');
|
---|
| 5 | const pLocate = require('p-locate');
|
---|
| 6 |
|
---|
| 7 | const fsStat = promisify(fs.stat);
|
---|
| 8 | const fsLStat = promisify(fs.lstat);
|
---|
| 9 |
|
---|
| 10 | const typeMappings = {
|
---|
| 11 | directory: 'isDirectory',
|
---|
| 12 | file: 'isFile'
|
---|
| 13 | };
|
---|
| 14 |
|
---|
| 15 | function checkType({type}) {
|
---|
| 16 | if (type in typeMappings) {
|
---|
| 17 | return;
|
---|
| 18 | }
|
---|
| 19 |
|
---|
| 20 | throw new Error(`Invalid type specified: ${type}`);
|
---|
| 21 | }
|
---|
| 22 |
|
---|
| 23 | const matchType = (type, stat) => type === undefined || stat[typeMappings[type]]();
|
---|
| 24 |
|
---|
| 25 | module.exports = async (paths, options) => {
|
---|
| 26 | options = {
|
---|
| 27 | cwd: process.cwd(),
|
---|
| 28 | type: 'file',
|
---|
| 29 | allowSymlinks: true,
|
---|
| 30 | ...options
|
---|
| 31 | };
|
---|
| 32 |
|
---|
| 33 | checkType(options);
|
---|
| 34 |
|
---|
| 35 | const statFn = options.allowSymlinks ? fsStat : fsLStat;
|
---|
| 36 |
|
---|
| 37 | return pLocate(paths, async path_ => {
|
---|
| 38 | try {
|
---|
| 39 | const stat = await statFn(path.resolve(options.cwd, path_));
|
---|
| 40 | return matchType(options.type, stat);
|
---|
| 41 | } catch {
|
---|
| 42 | return false;
|
---|
| 43 | }
|
---|
| 44 | }, options);
|
---|
| 45 | };
|
---|
| 46 |
|
---|
| 47 | module.exports.sync = (paths, options) => {
|
---|
| 48 | options = {
|
---|
| 49 | cwd: process.cwd(),
|
---|
| 50 | allowSymlinks: true,
|
---|
| 51 | type: 'file',
|
---|
| 52 | ...options
|
---|
| 53 | };
|
---|
| 54 |
|
---|
| 55 | checkType(options);
|
---|
| 56 |
|
---|
| 57 | const statFn = options.allowSymlinks ? fs.statSync : fs.lstatSync;
|
---|
| 58 |
|
---|
| 59 | for (const path_ of paths) {
|
---|
| 60 | try {
|
---|
| 61 | const stat = statFn(path.resolve(options.cwd, path_));
|
---|
| 62 |
|
---|
| 63 | if (matchType(options.type, stat)) {
|
---|
| 64 | return path_;
|
---|
| 65 | }
|
---|
| 66 | } catch {}
|
---|
| 67 | }
|
---|
| 68 | };
|
---|
Note:
See
TracBrowser
for help on using the repository browser.