UNPKG

1.36 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", "undefined"]);
9};
10
11// ---------------------------------------------------------
12// Sync
13// ---------------------------------------------------------
14
15const listSync = path => {
16 try {
17 return fs.readdirSync(path);
18 } catch (err) {
19 if (err.code === "ENOENT") {
20 // Doesn't exist. Return undefined instead of throwing.
21 return undefined;
22 }
23 throw err;
24 }
25};
26
27// ---------------------------------------------------------
28// Async
29// ---------------------------------------------------------
30
31const listAsync = path => {
32 return new Promise((resolve, reject) => {
33 fs.readdir(path)
34 .then(list => {
35 resolve(list);
36 })
37 .catch(err => {
38 if (err.code === "ENOENT") {
39 // Doesn't exist. Return undefined instead of throwing.
40 resolve(undefined);
41 } else {
42 reject(err);
43 }
44 });
45 });
46};
47
48// ---------------------------------------------------------
49// API
50// ---------------------------------------------------------
51
52exports.validateInput = validateInput;
53exports.sync = listSync;
54exports.async = listAsync;