copy.js 1.5 KB

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