copy.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. // don't allow src and dest to be the same
  15. var basePath = process.cwd()
  16. var currentPath = path.resolve(basePath, src)
  17. var targetPath = path.resolve(basePath, dest)
  18. if (currentPath === targetPath) return callback(new Error('Source and destination must not be the same.'))
  19. fs.lstat(src, function (err, stats) {
  20. if (err) return callback(err)
  21. var dir = null
  22. if (stats.isDirectory()) {
  23. var parts = dest.split(path.sep)
  24. parts.pop()
  25. dir = parts.join(path.sep)
  26. } else {
  27. dir = path.dirname(dest)
  28. }
  29. fs.exists(dir, function (dirExists) {
  30. if (dirExists) return ncp(src, dest, options, callback)
  31. mkdir.mkdirs(dir, function (err) {
  32. if (err) return callback(err)
  33. ncp(src, dest, options, callback)
  34. })
  35. })
  36. })
  37. }
  38. module.exports = copy