UNPKG

1.81 kBJavaScriptView Raw
1"use strict";
2
3const fs = require("./utils/fs");
4const write = require("./write");
5const validate = require("./utils/validate");
6
7const 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// SYNC
18// ---------------------------------------------------------
19
20const appendSync = (path, data, options) => {
21 try {
22 fs.appendFileSync(path, data, options);
23 } catch (err) {
24 if (err.code === "ENOENT") {
25 // Parent directory doesn't exist, so just pass the task to `write`,
26 // which will create the folder and file.
27 write.sync(path, data, options);
28 } else {
29 throw err;
30 }
31 }
32};
33
34// ---------------------------------------------------------
35// ASYNC
36// ---------------------------------------------------------
37
38const 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 // Parent directory doesn't exist, so just pass the task to `write`,
45 // which will create the folder and file.
46 write.async(path, data, options).then(resolve, reject);
47 } else {
48 reject(err);
49 }
50 });
51 });
52};
53
54// ---------------------------------------------------------
55// API
56// ---------------------------------------------------------
57
58exports.validateInput = validateInput;
59exports.sync = appendSync;
60exports.async = appendAsync;