index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /**
  2. * Module dependencies.
  3. */
  4. var fs = require('fs');
  5. try { fs = require('graceful-fs'); } catch (e) {}
  6. /**
  7. * Magic number.
  8. */
  9. var MAX_BUFFER = 1024;
  10. /**
  11. * Export `cp`.
  12. */
  13. exports = module.exports = cp;
  14. /**
  15. * Export `sync`.
  16. */
  17. exports.sync = sync;
  18. /**
  19. * Copy `src` to `dest`, invoking `cb(err)` when done.
  20. *
  21. * @param {String} src
  22. * @param {String} dest
  23. * @param {Function} [cb]
  24. * @api public
  25. */
  26. function cp(src, dest, cb) {
  27. // yield support
  28. if ('function' != typeof cb) return thunk;
  29. var complete = false;
  30. var read = fs.createReadStream(src);
  31. var write = fs.createWriteStream(dest);
  32. write.on('error', done);
  33. write.on('close', done);
  34. read.on('error', done);
  35. read.pipe(write);
  36. // done callback
  37. function done(err) {
  38. if (!complete) {
  39. complete = true;
  40. read.destroy();
  41. write.destroy();
  42. cb(err);
  43. }
  44. }
  45. // thunk-ified
  46. function thunk(done) {
  47. cp(src, dest, done);
  48. }
  49. }
  50. /**
  51. * Synchronously copy file `src` to `dest`
  52. *
  53. * @param {String} src
  54. * @param {String} dest
  55. * @api public
  56. */
  57. function sync(src, dest) {
  58. if (!fs.existsSync(src)) {
  59. throw new Error('no such file or directory: ' + src);
  60. }
  61. var buffer = new Buffer(MAX_BUFFER);
  62. var bytesRead = MAX_BUFFER;
  63. var pos = 0;
  64. var read = fs.openSync(src, 'r');
  65. var write = fs.openSync(dest, 'w');
  66. while (MAX_BUFFER == bytesRead) {
  67. bytesRead = fs.readSync(read, buffer, 0, MAX_BUFFER, pos);
  68. fs.writeSync(write, buffer, 0, bytesRead);
  69. pos += bytesRead;
  70. }
  71. fs.closeSync(read);
  72. fs.closeSync(write);
  73. }