symlink.js
2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
var path = require('path')
var fs = require('graceful-fs')
var _mkdirs = require('../mkdirs')
var mkdirs = _mkdirs.mkdirs
var mkdirsSync = _mkdirs.mkdirsSync
var _symlinkPaths = require('./symlink-paths')
var symlinkPaths = _symlinkPaths.symlinkPaths
var symlinkPathsSync = _symlinkPaths.symlinkPathsSync
var _symlinkType = require('./symlink-type')
var symlinkType = _symlinkType.symlinkType
var symlinkTypeSync = _symlinkType.symlinkTypeSync
function createSymlink (srcpath, dstpath, type, callback) {
callback = (typeof type === 'function') ? type : callback
type = (typeof type === 'function') ? false : type
fs.exists(dstpath, function (destinationExists) {
if (destinationExists) return callback(null)
symlinkPaths(srcpath, dstpath, function (err, relative) {
if (err) return callback(err)
srcpath = relative.toDst
symlinkType(relative.toCwd, type, function (err, type) {
if (err) return callback(err)
var dir = path.dirname(dstpath)
fs.exists(dir, function (dirExists) {
if (dirExists) return fs.symlink(srcpath, dstpath, type, callback)
mkdirs(dir, function (err) {
if (err) return callback(err)
fs.symlink(srcpath, dstpath, type, callback)
})
})
})
})
})
}
function createSymlinkSync (srcpath, dstpath, type, callback) {
callback = (typeof type === 'function') ? type : callback
type = (typeof type === 'function') ? false : type
var destinationExists = fs.existsSync(dstpath)
if (destinationExists) return undefined
var relative = symlinkPathsSync(srcpath, dstpath)
srcpath = relative.toDst
type = symlinkTypeSync(relative.toCwd, type)
var dir = path.dirname(dstpath)
var exists = fs.existsSync(dir)
if (exists) return fs.symlinkSync(srcpath, dstpath, type)
mkdirsSync(dir)
return fs.symlinkSync(srcpath, dstpath, type)
}
module.exports = {
createSymlink: createSymlink,
createSymlinkSync: createSymlinkSync,
// alias
ensureSymlink: createSymlink,
ensureSymlinkSync: createSymlinkSync
}