copy-sync.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /**
  2. * @author Toru Nagashima
  3. * @copyright 2016 Toru Nagashima. All rights reserved.
  4. * See LICENSE file in root directory for full license.
  5. */
  6. "use strict";
  7. var _require = require("safe-buffer");
  8. var Buffer = _require.Buffer;
  9. var fs = require("fs");
  10. var mkdirSync = require("mkdirp").sync;
  11. var MAX_BUFFER = 2048;
  12. /**
  13. * @param {string} src - A path of the source file.
  14. * @param {string} dst - A path of the destination file.
  15. * @returns {void}
  16. * @private
  17. */
  18. function copyBodySync(src, dst) {
  19. var buffer = Buffer.allocUnsafe(MAX_BUFFER);
  20. var bytesRead = MAX_BUFFER;
  21. var pos = 0;
  22. var input = fs.openSync(src, "r");
  23. try {
  24. var output = fs.openSync(dst, "w");
  25. try {
  26. while (MAX_BUFFER === bytesRead) {
  27. bytesRead = fs.readSync(input, buffer, 0, MAX_BUFFER, pos);
  28. fs.writeSync(output, buffer, 0, bytesRead);
  29. pos += bytesRead;
  30. }
  31. } finally {
  32. fs.closeSync(output);
  33. }
  34. } finally {
  35. fs.closeSync(input);
  36. }
  37. }
  38. /**
  39. * @param {string} src - A path of the source file.
  40. * @param {string} dst - A path of the destination file.
  41. * @param {object} options - Options.
  42. * @param {boolean} options.preserve - The flag to copy attributes.
  43. * @param {boolean} options.update - The flag to disallow overwriting.
  44. * @returns {void}
  45. * @private
  46. */
  47. module.exports = function copySync(src, dst, _ref) {
  48. var preserve = _ref.preserve;
  49. var update = _ref.update;
  50. var stat = fs.statSync(src);
  51. if (update) {
  52. try {
  53. var dstStat = fs.statSync(dst);
  54. if (dstStat.mtime.getTime() > stat.mtime.getTime()) {
  55. // Don't overwrite because the file on destination is newer than
  56. // the source file.
  57. return;
  58. }
  59. } catch (_err) {
  60. // ignore - The file may not exist.
  61. }
  62. }
  63. if (stat.isDirectory()) {
  64. mkdirSync(dst);
  65. } else {
  66. copyBodySync(src, dst);
  67. }
  68. fs.chmodSync(dst, stat.mode);
  69. if (preserve) {
  70. fs.chownSync(dst, stat.uid, stat.gid);
  71. fs.utimesSync(dst, stat.atime, stat.mtime);
  72. }
  73. };