1 | "use strict";
|
2 |
|
3 | const pathUtil = require("path");
|
4 | const os = require("os");
|
5 | const crypto = require("crypto");
|
6 | const dir = require("./dir");
|
7 | const fs = require("./utils/fs");
|
8 | const validate = require("./utils/validate");
|
9 |
|
10 | const validateInput = (methodName, options) => {
|
11 | const methodSignature = `${methodName}([options])`;
|
12 | validate.options(methodSignature, "options", options, {
|
13 | prefix: ["string"],
|
14 | basePath: ["string"]
|
15 | });
|
16 | };
|
17 |
|
18 | const 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 |
|
34 | const randomStringLength = 32;
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 | const 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 |
|
50 | try {
|
51 | fs.mkdirSync(dirPath);
|
52 | } catch (err) {
|
53 |
|
54 | if (err.code === "ENOENT") {
|
55 | dir.sync(dirPath);
|
56 | } else {
|
57 | throw err;
|
58 | }
|
59 | }
|
60 | return dirPath;
|
61 | };
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 | const 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 |
|
80 | fs.mkdir(dirPath, err => {
|
81 | if (err) {
|
82 |
|
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 |
|
101 |
|
102 |
|
103 | exports.validateInput = validateInput;
|
104 | exports.sync = tmpDirSync;
|
105 | exports.async = tmpDirAsync;
|