UNPKG

3.03 kBJavaScriptView Raw
1"use strict";
2
3const pathUtil = require("path");
4const os = require("os");
5const crypto = require("crypto");
6const dir = require("./dir");
7const fs = require("./utils/fs");
8const validate = require("./utils/validate");
9
10const validateInput = (methodName, options) => {
11 const methodSignature = `${methodName}([options])`;
12 validate.options(methodSignature, "options", options, {
13 prefix: ["string"],
14 basePath: ["string"]
15 });
16};
17
18const getOptionsDefaults = (passedOptions, cwdPath) => {
19 passedOptions = passedOptions || {};
20 const options = {};
21 if (typeof passedOptions.prefix !== "string") {
22 options.prefix = "";
23 } else {
24 options.prefix = passedOptions.prefix;
25 }
26 if (typeof passedOptions.basePath === "string") {
27 options.basePath = pathUtil.resolve(cwdPath, passedOptions.basePath);
28 } else {
29 options.basePath = os.tmpdir();
30 }
31 return options;
32};
33
34const randomStringLength = 32;
35
36// ---------------------------------------------------------
37// Sync
38// ---------------------------------------------------------
39
40const tmpDirSync = (cwdPath, passedOptions) => {
41 const options = getOptionsDefaults(passedOptions, cwdPath);
42 const randomString = crypto
43 .randomBytes(randomStringLength / 2)
44 .toString("hex");
45 const dirPath = pathUtil.join(
46 options.basePath,
47 options.prefix + randomString
48 );
49 // Let's assume everything will go well, do the directory fastest way possible
50 try {
51 fs.mkdirSync(dirPath);
52 } catch (err) {
53 // Something went wrong, try to recover by using more sophisticated approach
54 if (err.code === "ENOENT") {
55 dir.sync(dirPath);
56 } else {
57 throw err;
58 }
59 }
60 return dirPath;
61};
62
63// ---------------------------------------------------------
64// Async
65// ---------------------------------------------------------
66
67const tmpDirAsync = (cwdPath, passedOptions) => {
68 return new Promise((resolve, reject) => {
69 const options = getOptionsDefaults(passedOptions, cwdPath);
70 crypto.randomBytes(randomStringLength / 2, (err, bytes) => {
71 if (err) {
72 reject(err);
73 } else {
74 const randomString = bytes.toString("hex");
75 const dirPath = pathUtil.join(
76 options.basePath,
77 options.prefix + randomString
78 );
79 // Let's assume everything will go well, do the directory fastest way possible
80 fs.mkdir(dirPath, err => {
81 if (err) {
82 // Something went wrong, try to recover by using more sophisticated approach
83 if (err.code === "ENOENT") {
84 dir.async(dirPath).then(() => {
85 resolve(dirPath);
86 }, reject);
87 } else {
88 reject(err);
89 }
90 } else {
91 resolve(dirPath);
92 }
93 });
94 }
95 });
96 });
97};
98
99// ---------------------------------------------------------
100// API
101// ---------------------------------------------------------
102
103exports.validateInput = validateInput;
104exports.sync = tmpDirSync;
105exports.async = tmpDirAsync;