uploadSftp.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. var ClientLib = require('scp2');
  3. var client = new ClientLib.Client();
  4. function UploadSftp(options) {
  5. this.options = options;
  6. }
  7. UploadSftp.prototype.apply = function (callbck) {
  8. var self = this;
  9. var remotePath = self.options.remotePath;
  10. var path = self.options.path;
  11. var username = self.options.username;
  12. var host = self.options.host;
  13. var password = self.options.password;
  14. var port = self.options.port || '22';
  15. var verbose = self.options.verbose;
  16. var startTime;
  17. var endTime;
  18. client.on('connect', function () {
  19. // console.log('connected');
  20. });
  21. client.on('ready', function () {
  22. // console.log('ready');
  23. startTime = new Date();
  24. console.log('[Start Uploading] ' + startTime);
  25. });
  26. client.on('transfer', function (buf, up, total) {});
  27. client.on('write', function (p) {
  28. if (verbose) {
  29. console.log('Transfer ' + p.source + ' => ' + p.destination);
  30. }
  31. });
  32. client.on('end', function () {
  33. endTime = new Date();
  34. console.log('[End Uploading] ' + new Date());
  35. });
  36. client.on('error', function (err) {
  37. console.log('[Error] ' + err);
  38. });
  39. client.on('close', function () {
  40. console.log(
  41. 'Transfer with SFTP Completed in [' +
  42. (+endTime - +startTime) / 1000 +
  43. '] seconds!',
  44. );
  45. callbck && callbck();
  46. });
  47. var srcPath = path;
  48. var destPath =
  49. username + ':' + password + '@' + host + ':' + port + ':' + remotePath;
  50. uploadByDir(srcPath, destPath, client);
  51. };
  52. /**
  53. * [uploadByDir: Upload Directory Directory & Cannot Get Detailed Uploading Info for Files]
  54. * @param {[String]} src [description]
  55. * @param {[String]} dest [description]
  56. * @param {[Object]} client [description]
  57. */
  58. function uploadByDir(src, dest, client) {
  59. ClientLib.scp(src, dest, client, function (err) {
  60. if (err) {
  61. console.log(err);
  62. }
  63. });
  64. }
  65. module.exports = UploadSftp;