symlink.js 2.0 KB

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