UNPKG

1.5 kBJavaScriptView Raw
1"use strict";
2
3const fs = require("./utils/fs");
4const validate = require("./utils/validate");
5
6const validateInput = (methodName, path) => {
7 const methodSignature = `${methodName}(path)`;
8 validate.argument(methodSignature, "path", path, ["string"]);
9};
10
11// ---------------------------------------------------------
12// Sync
13// ---------------------------------------------------------
14
15const existsSync = path => {
16 try {
17 const stat = fs.statSync(path);
18 if (stat.isDirectory()) {
19 return "dir";
20 } else if (stat.isFile()) {
21 return "file";
22 }
23 return "other";
24 } catch (err) {
25 if (err.code !== "ENOENT") {
26 throw err;
27 }
28 }
29
30 return false;
31};
32
33// ---------------------------------------------------------
34// Async
35// ---------------------------------------------------------
36
37const existsAsync = path => {
38 return new Promise((resolve, reject) => {
39 fs.stat(path)
40 .then(stat => {
41 if (stat.isDirectory()) {
42 resolve("dir");
43 } else if (stat.isFile()) {
44 resolve("file");
45 } else {
46 resolve("other");
47 }
48 })
49 .catch(err => {
50 if (err.code === "ENOENT") {
51 resolve(false);
52 } else {
53 reject(err);
54 }
55 });
56 });
57};
58
59// ---------------------------------------------------------
60// API
61// ---------------------------------------------------------
62
63exports.validateInput = validateInput;
64exports.sync = existsSync;
65exports.async = existsAsync;