copy-file-sync.js 882 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. var fs = require('graceful-fs')
  2. var BUF_LENGTH = 64 * 1024
  3. var _buff = new Buffer(BUF_LENGTH)
  4. function copyFileSync (srcFile, destFile, options) {
  5. var clobber = options.clobber
  6. var preserveTimestamps = options.preserveTimestamps
  7. if (fs.existsSync(destFile)) {
  8. if (clobber) {
  9. fs.chmodSync(destFile, parseInt('777', 8))
  10. fs.unlinkSync(destFile)
  11. } else {
  12. throw Error('EEXIST')
  13. }
  14. }
  15. var fdr = fs.openSync(srcFile, 'r')
  16. var stat = fs.fstatSync(fdr)
  17. var fdw = fs.openSync(destFile, 'w', stat.mode)
  18. var bytesRead = 1
  19. var pos = 0
  20. while (bytesRead > 0) {
  21. bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
  22. fs.writeSync(fdw, _buff, 0, bytesRead)
  23. pos += bytesRead
  24. }
  25. if (preserveTimestamps) {
  26. fs.futimesSync(fdw, stat.atime, stat.mtime)
  27. }
  28. fs.closeSync(fdr)
  29. fs.closeSync(fdw)
  30. }
  31. module.exports = copyFileSync