uploadSftp.js 2.0 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. });
  28. client.on('write', function (p) {
  29. if (verbose) {
  30. console.log('Transfer ' + p.source + ' => ' + p.destination);
  31. }
  32. });
  33. client.on('end', function () {
  34. endTime = new Date();
  35. console.log('[End Uploading] ' + new Date());
  36. });
  37. client.on('error', function (err) {
  38. console.log('[Error] ' + err);
  39. });
  40. client.on('close', function () {
  41. console.log('Transfer with SFTP Completed in [' + (+endTime - +startTime) / 1000 + '] seconds!');
  42. callbck && callbck();
  43. });
  44. var srcPath = path;
  45. var destPath = username + ':' + password + '@' + host + ':' + port + ':' + remotePath;
  46. uploadByDir(srcPath, destPath, client);
  47. };
  48. /**
  49. * [uploadByDir: Upload Directory Directory & Cannot Get Detailed Uploading Info for Files]
  50. * @param {[String]} src [description]
  51. * @param {[String]} dest [description]
  52. * @param {[Object]} client [description]
  53. */
  54. function uploadByDir(src, dest, client) {
  55. ClientLib.scp(src, dest, client,
  56. function (err) {
  57. if (err) {
  58. console.log(err);
  59. }
  60. }
  61. );
  62. }
  63. module.exports = UploadSftp;