1 | "use strict";
|
2 |
|
3 | const fs = require("./utils/fs");
|
4 | const write = require("./write");
|
5 | const validate = require("./utils/validate");
|
6 |
|
7 | const validateInput = (methodName, path, data, options) => {
|
8 | const methodSignature = `${methodName}(path, data, [options])`;
|
9 | validate.argument(methodSignature, "path", path, ["string"]);
|
10 | validate.argument(methodSignature, "data", data, ["string", "buffer"]);
|
11 | validate.options(methodSignature, "options", options, {
|
12 | mode: ["string", "number"]
|
13 | });
|
14 | };
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | const appendSync = (path, data, options) => {
|
21 | try {
|
22 | fs.appendFileSync(path, data, options);
|
23 | } catch (err) {
|
24 | if (err.code === "ENOENT") {
|
25 |
|
26 |
|
27 | write.sync(path, data, options);
|
28 | } else {
|
29 | throw err;
|
30 | }
|
31 | }
|
32 | };
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | const appendAsync = (path, data, options) => {
|
39 | return new Promise((resolve, reject) => {
|
40 | fs.appendFile(path, data, options)
|
41 | .then(resolve)
|
42 | .catch(err => {
|
43 | if (err.code === "ENOENT") {
|
44 |
|
45 |
|
46 | write.async(path, data, options).then(resolve, reject);
|
47 | } else {
|
48 | reject(err);
|
49 | }
|
50 | });
|
51 | });
|
52 | };
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 | exports.validateInput = validateInput;
|
59 | exports.sync = appendSync;
|
60 | exports.async = appendAsync;
|