UNPKG

1.81 kBJavaScriptView Raw
1"use strict";
2
3const pathUtil = require("path");
4const fs = require("./utils/fs");
5const validate = require("./utils/validate");
6const dir = require("./dir");
7
8const validateInput = (methodName, symlinkValue, path) => {
9 const methodSignature = `${methodName}(symlinkValue, path)`;
10 validate.argument(methodSignature, "symlinkValue", symlinkValue, ["string"]);
11 validate.argument(methodSignature, "path", path, ["string"]);
12};
13
14// ---------------------------------------------------------
15// Sync
16// ---------------------------------------------------------
17
18const symlinkSync = (symlinkValue, path) => {
19 try {
20 fs.symlinkSync(symlinkValue, path);
21 } catch (err) {
22 if (err.code === "ENOENT") {
23 // Parent directories don't exist. Just create them and rety.
24 dir.createSync(pathUtil.dirname(path));
25 fs.symlinkSync(symlinkValue, path);
26 } else {
27 throw err;
28 }
29 }
30};
31
32// ---------------------------------------------------------
33// Async
34// ---------------------------------------------------------
35
36const symlinkAsync = (symlinkValue, path) => {
37 return new Promise((resolve, reject) => {
38 fs.symlink(symlinkValue, path)
39 .then(resolve)
40 .catch(err => {
41 if (err.code === "ENOENT") {
42 // Parent directories don't exist. Just create them and rety.
43 dir
44 .createAsync(pathUtil.dirname(path))
45 .then(() => {
46 return fs.symlink(symlinkValue, path);
47 })
48 .then(resolve, reject);
49 } else {
50 reject(err);
51 }
52 });
53 });
54};
55
56// ---------------------------------------------------------
57// API
58// ---------------------------------------------------------
59
60exports.validateInput = validateInput;
61exports.sync = symlinkSync;
62exports.async = symlinkAsync;