No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

move.js 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict'
  2. const fs = require('graceful-fs')
  3. const path = require('path')
  4. const copy = require('../copy').copy
  5. const remove = require('../remove').remove
  6. const mkdirp = require('../mkdirs').mkdirp
  7. const pathExists = require('../path-exists').pathExists
  8. const stat = require('../util/stat')
  9. function move (src, dest, opts, cb) {
  10. if (typeof opts === 'function') {
  11. cb = opts
  12. opts = {}
  13. }
  14. opts = opts || {}
  15. const overwrite = opts.overwrite || opts.clobber || false
  16. stat.checkPaths(src, dest, 'move', opts, (err, stats) => {
  17. if (err) return cb(err)
  18. const { srcStat, isChangingCase = false } = stats
  19. stat.checkParentPaths(src, srcStat, dest, 'move', err => {
  20. if (err) return cb(err)
  21. if (isParentRoot(dest)) return doRename(src, dest, overwrite, isChangingCase, cb)
  22. mkdirp(path.dirname(dest), err => {
  23. if (err) return cb(err)
  24. return doRename(src, dest, overwrite, isChangingCase, cb)
  25. })
  26. })
  27. })
  28. }
  29. function isParentRoot (dest) {
  30. const parent = path.dirname(dest)
  31. const parsedPath = path.parse(parent)
  32. return parsedPath.root === parent
  33. }
  34. function doRename (src, dest, overwrite, isChangingCase, cb) {
  35. if (isChangingCase) return rename(src, dest, overwrite, cb)
  36. if (overwrite) {
  37. return remove(dest, err => {
  38. if (err) return cb(err)
  39. return rename(src, dest, overwrite, cb)
  40. })
  41. }
  42. pathExists(dest, (err, destExists) => {
  43. if (err) return cb(err)
  44. if (destExists) return cb(new Error('dest already exists.'))
  45. return rename(src, dest, overwrite, cb)
  46. })
  47. }
  48. function rename (src, dest, overwrite, cb) {
  49. fs.rename(src, dest, err => {
  50. if (!err) return cb()
  51. if (err.code !== 'EXDEV') return cb(err)
  52. return moveAcrossDevice(src, dest, overwrite, cb)
  53. })
  54. }
  55. function moveAcrossDevice (src, dest, overwrite, cb) {
  56. const opts = {
  57. overwrite,
  58. errorOnExist: true
  59. }
  60. copy(src, dest, opts, err => {
  61. if (err) return cb(err)
  62. return remove(src, cb)
  63. })
  64. }
  65. module.exports = move