copy.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. 'use strict'
  2. const fs = require('graceful-fs')
  3. const path = require('path')
  4. const ncp = require('./ncp')
  5. const mkdir = require('../mkdirs')
  6. const pathExists = require('../path-exists').pathExists
  7. function copy (src, dest, options, callback) {
  8. if (typeof options === 'function' && !callback) {
  9. callback = options
  10. options = {}
  11. } else if (typeof options === 'function' || options instanceof RegExp) {
  12. options = {filter: options}
  13. }
  14. callback = callback || function () {}
  15. options = options || {}
  16. // Warn about using preserveTimestamps on 32-bit node:
  17. if (options.preserveTimestamps && process.arch === 'ia32') {
  18. console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
  19. see https://github.com/jprichardson/node-fs-extra/issues/269`)
  20. }
  21. // don't allow src and dest to be the same
  22. const basePath = process.cwd()
  23. const currentPath = path.resolve(basePath, src)
  24. const targetPath = path.resolve(basePath, dest)
  25. if (currentPath === targetPath) return callback(new Error('Source and destination must not be the same.'))
  26. fs.lstat(src, (err, stats) => {
  27. if (err) return callback(err)
  28. let dir = null
  29. if (stats.isDirectory()) {
  30. const parts = dest.split(path.sep)
  31. parts.pop()
  32. dir = parts.join(path.sep)
  33. } else {
  34. dir = path.dirname(dest)
  35. }
  36. pathExists(dir, (err, dirExists) => {
  37. if (err) return callback(err)
  38. if (dirExists) return ncp(src, dest, options, callback)
  39. mkdir.mkdirs(dir, err => {
  40. if (err) return callback(err)
  41. ncp(src, dest, options, callback)
  42. })
  43. })
  44. })
  45. }
  46. module.exports = copy