ssh2-sftp-client 9.0.1 → 9.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,65 +1,66 @@
1
- - [Overview](#org19c31e8)
2
- - [Version 9.x Changes](#orgc330d84)
3
- - [Installation](#org7c63f6a)
4
- - [Basic Usage](#orgb99a07c)
5
- - [Documentation](#org5550f37)
6
- - [Specifying Paths](#org2f0a3a6)
7
- - [Methods](#org8d230d5)
8
- - [new SftpClient(name) ===> SFTP client object](#orgc8b55d7)
9
- - [connect(config) ===> SFTP object](#org42512fb)
10
- - [list(path, filter) ==> Array[object]](#orgbe9e165)
11
- - [exists(path) ==> boolean](#org14dee5e)
12
- - [stat(path) ==> object](#orga0033c0)
13
- - [get(path, dst, options) ==> String|Stream|Buffer](#org02a3dc5)
14
- - [fastGet(remotePath, localPath, options) ===> string](#orge9f875d)
15
- - [put(src, remotePath, options) ==> string](#orgc7941ea)
16
- - [fastPut(localPath, remotePath, options) ==> string](#org8f8794d)
17
- - [append(input, remotePath, options) ==> string](#org82c75b5)
18
- - [mkdir(path, recursive) ==> string](#org42c5eeb)
19
- - [rmdir(path, recursive) ==> string](#orgd0aa59d)
20
- - [delete(path, noErrorOK) ==> string](#orgb496048)
21
- - [rename(fromPath, toPath) ==> string](#org1a2be8f)
22
- - [posixRename(fromPath, toPath) ==> string](#org571c0b9)
23
- - [chmod(path, mode) ==> string](#org02d64a4)
24
- - [realPath(path) ===> string](#org008d567)
25
- - [cwd() ==> string](#org7033d28)
26
- - [uploadDir(srcDir, dstDir, options) ==> string](#orgfa0102a)
27
- - [downloadDir(srcDir, dstDir, options) ==> string](#orgefe6fc6)
28
- - [createReadStream(remotePath, options)) ==> stream object](#org783e363)
29
- - [createWriteStream(remotePath, options) ==> stream object](#orgf45313d)
30
- - [rcopy(srcPath, dstPath) ==> string](#orga31c8c1)
31
- - [end() ==> boolean](#org4d02fde)
32
- - [Add and Remove Listeners](#orge5769d3)
33
- - [Platform Quirks & Warnings](#org3e6ddf9)
34
- - [Server Capabilities](#org61f0fe5)
35
- - [Promises, Events & Managing Exceptions](#orga7d6067)
36
- - [Adding Custom Handlers](#orgc08d427)
37
- - [Windows Based Servers](#org5439468)
38
- - [Don't Re-use SftpClient Objects](#orgae9129c)
39
- - [FAQ](#org3761660)
40
- - [Remote server drops connections with only an end event](#org1e669d1)
41
- - [How can I pass writable stream as dst for get method?](#org71d5bab)
42
- - [How can I upload files without having to specify a password?](#orgaafc964)
43
- - [How can I connect through a Socks Proxy](#orgebf85e2)
44
- - [Timeout while waiting for handshake or handshake errors](#org528d9ea)
45
- - [How can I limit upload/download speed](#org3b6ff20)
46
- - [Connection hangs or fails for larger files](#orgb5e285f)
47
- - [Examples](#org18ce0c2)
48
- - [Troubleshooting](#orgf4b6c80)
49
- - [Common Errors](#orga419582)
50
- - [Not returning the promise in a `then()` block](#orgd5f3557)
51
- - [Mixing Promise Chains and Async/Await](#org557d1c5)
52
- - [Try/catch and Error Handlers](#org2bf9a3a)
53
- - [Server Differences](#org89795d7)
54
- - [Avoid Concurrent Operations](#orgbec08b0)
55
- - [Debugging Support](#org124cfc9)
56
- - [Logging Issues](#org5f3c941)
57
- - [Pull Requests](#org6e82efc)
58
- - [Contributors](#org680b5c2)
59
-
60
-
61
-
62
- <a id="org19c31e8"></a>
1
+ - [Overview](#org50de852)
2
+ - [Version 9.x Changes](#orgaeda8f1)
3
+ - [Installation](#orgf01877e)
4
+ - [Basic Usage](#org5950004)
5
+ - [Documentation](#org5057006)
6
+ - [Specifying Paths](#org4ef62d6)
7
+ - [Methods](#org197917e)
8
+ - [new SftpClient(name) ===> SFTP client object](#orge668bfa)
9
+ - [connect(config) ===> SFTP object](#orgcf80c45)
10
+ - [list(path, filter) ==> Array[object]](#org329ff56)
11
+ - [exists(path) ==> boolean](#orgc52d8a8)
12
+ - [stat(path) ==> object](#orgcfa8682)
13
+ - [get(path, dst, options) ==> String|Stream|Buffer](#orgbe46842)
14
+ - [fastGet(remotePath, localPath, options) ===> string](#org740cf5c)
15
+ - [put(src, remotePath, options) ==> string](#org429e96a)
16
+ - [fastPut(localPath, remotePath, options) ==> string](#orgcab50c6)
17
+ - [append(input, remotePath, options) ==> string](#orgc15d676)
18
+ - [mkdir(path, recursive) ==> string](#org6fab860)
19
+ - [rmdir(path, recursive) ==> string](#org520f6bc)
20
+ - [delete(path, noErrorOK) ==> string](#org1be8ca9)
21
+ - [rename(fromPath, toPath) ==> string](#org3d89131)
22
+ - [posixRename(fromPath, toPath) ==> string](#org58dfee5)
23
+ - [chmod(path, mode) ==> string](#orgb319965)
24
+ - [realPath(path) ===> string](#orgf665476)
25
+ - [cwd() ==> string](#org409acd1)
26
+ - [uploadDir(srcDir, dstDir, options) ==> string](#org668b085)
27
+ - [downloadDir(srcDir, dstDir, options) ==> string](#org395ac4e)
28
+ - [createReadStream(remotePath, options)) ==> stream object](#org8a73b83)
29
+ - [createWriteStream(remotePath, options) ==> stream object](#orgb71fb72)
30
+ - [rcopy(srcPath, dstPath) ==> string](#org936f530)
31
+ - [end() ==> boolean](#org62a8323)
32
+ - [Add and Remove Listeners](#orgd1ebc36)
33
+ - [Platform Quirks & Warnings](#orgdfff943)
34
+ - [Server Capabilities](#org886fe2e)
35
+ - [Issues with `fastPut()` and `fastGet()` Methods](#org1719a52)
36
+ - [Promises, Events & Managing Exceptions](#org42a51fc)
37
+ - [Adding Custom Handlers](#orgd50a35a)
38
+ - [Windows Based Servers](#org7b0987f)
39
+ - [Don't Re-use SftpClient Objects](#orgbe548c2)
40
+ - [FAQ](#orgfddb94b)
41
+ - [Remote server drops connections with only an end event](#orgbd2a31e)
42
+ - [How can I pass writable stream as dst for get method?](#org9d72a61)
43
+ - [How can I upload files without having to specify a password?](#org9fda086)
44
+ - [How can I connect through a Socks Proxy](#org2ccc5e8)
45
+ - [Timeout while waiting for handshake or handshake errors](#org5306b6f)
46
+ - [How can I limit upload/download speed](#org3a77529)
47
+ - [Connection hangs or fails for larger files](#org68eedc7)
48
+ - [Examples](#orgd436fa7)
49
+ - [Troubleshooting](#orge21d870)
50
+ - [Common Errors](#org287b86f)
51
+ - [Not returning the promise in a `then()` block](#org20a99bb)
52
+ - [Mixing Promise Chains and Async/Await](#org51482b4)
53
+ - [Try/catch and Error Handlers](#orgb9a556a)
54
+ - [Server Differences](#org0d148f0)
55
+ - [Avoid Concurrent Operations](#orgf115391)
56
+ - [Debugging Support](#orgc7c437f)
57
+ - [Logging Issues](#orgc79ef28)
58
+ - [Pull Requests](#org64bd2a2)
59
+ - [Contributors](#org709b0f9)
60
+
61
+
62
+
63
+ <a id="org50de852"></a>
63
64
 
64
65
  # Overview
65
66
 
@@ -67,17 +68,21 @@ an SFTP client for node.js, a wrapper around [SSH2](https://github.com/mscdex/ss
67
68
 
68
69
  Documentation on the methods and available options in the underlying modules can be found on the [SSH2](https://github.com/mscdex/ssh2) project pages.
69
70
 
70
- Current stable release is **v9.0.1**.
71
+ Current stable release is **v9.0.2**.
71
72
 
72
73
  Code has been tested against Node versions 14.19.1, 16.15.0 and 18.1.0
73
74
 
74
75
  Node versions < 14.x are not supported.
75
76
 
76
77
 
77
- <a id="orgc330d84"></a>
78
+ <a id="orgaeda8f1"></a>
78
79
 
79
80
  ## Version 9.x Changes
80
81
 
82
+ - Change the default end and close handlers not to throw error or reject promises. Previously, an end or close event would cause an error to be raised or a promise to be rejected if the event was deemed to be *unexpected*. However, classification of events as being unexpected was unreliable and didn't add much real value. Both these handlers will now invalidate the sftp connection object and log that the event fired and nothing else.
83
+ - Changed when event handled flags are reset. Now they are reset after a new set of temporary listeners are added.
84
+ - Don't throw an error when calling end() if there is no active sftp connection. It does no harm to call end() when there is no connection, so no need to raise an error.
85
+ - Use nullish coalescing when setting retry parameters instead of or'ing with defaults. Allows setting values to 0.
81
86
  - **Breaking Change**: This version uses syntax not supported in node versions prior to v14. Therefore, node versions less than v14 will not work.
82
87
  - **Breaking Change**: This `list()` method no longer accepts a regular expression for filtering the entries to be returned. You can now specify a filter function instead. The function is called for each item in the list of items to be returned, passing in the item object as its only argument. Essentially, this is just a call to `Array.filter()`, so the filter function should behave in the same way i.e. return true for items to be retained and false for those to be dropped.
83
88
  - **Breaking Change**: The ability to set `autoClose` on read and write streams and the ability to set `end` on `pipe` operations has been removed. These options caused confusion for users and were too easy to get wrong, plus it made the methods overly complicated. For those use-cases where you want to control streams at a low level, two new methods have been added, `createReadStream()` and `createWriteStream()`. However, it should be noted that client code is 100% responsible for managing streams obtained using these methods. Use at your own risk!
@@ -89,7 +94,7 @@ Node versions < 14.x are not supported.
89
94
  - Bumped ssh2 version to 1.11.0
90
95
 
91
96
 
92
- <a id="org7c63f6a"></a>
97
+ <a id="orgf01877e"></a>
93
98
 
94
99
  # Installation
95
100
 
@@ -98,7 +103,7 @@ npm install ssh2-sftp-client
98
103
  ```
99
104
 
100
105
 
101
- <a id="orgb99a07c"></a>
106
+ <a id="org5950004"></a>
102
107
 
103
108
  # Basic Usage
104
109
 
@@ -121,7 +126,7 @@ sftp.connect({
121
126
  ```
122
127
 
123
128
 
124
- <a id="org5550f37"></a>
129
+ <a id="org5057006"></a>
125
130
 
126
131
  # Documentation
127
132
 
@@ -130,7 +135,7 @@ The connection options are the same as those offered by the underlying SSH2 modu
130
135
  All the methods will return a Promise, except for `on()` and `removeListener()`, which are typically only used in special use cases.
131
136
 
132
137
 
133
- <a id="org2f0a3a6"></a>
138
+ <a id="org4ef62d6"></a>
134
139
 
135
140
  ## Specifying Paths
136
141
 
@@ -163,12 +168,12 @@ client.put('/home/fred/test.txt', '/remote/dir/test-copy.txt');
163
168
  This will copy the local file `test.txt` to the remote file `test-copy.txt` in the directory `/remote/dir`.
164
169
 
165
170
 
166
- <a id="org8d230d5"></a>
171
+ <a id="org197917e"></a>
167
172
 
168
173
  ## Methods
169
174
 
170
175
 
171
- <a id="orgc8b55d7"></a>
176
+ <a id="orge668bfa"></a>
172
177
 
173
178
  ### new SftpClient(name) ===> SFTP client object
174
179
 
@@ -207,7 +212,7 @@ Constructor to create a new `ssh2-sftp-client` object. An optional `name` string
207
212
  ```
208
213
 
209
214
 
210
- <a id="org42512fb"></a>
215
+ <a id="orgcf80c45"></a>
211
216
 
212
217
  ### connect(config) ===> SFTP object
213
218
 
@@ -273,7 +278,7 @@ Connect to an sftp server. Full documentation for connection options is availabl
273
278
  ```
274
279
 
275
280
 
276
- <a id="orgbe9e165"></a>
281
+ <a id="org329ff56"></a>
277
282
 
278
283
  ### list(path, filter) ==> Array[object]
279
284
 
@@ -344,7 +349,7 @@ Retrieves a directory listing. This method returns a Promise, which once realise
344
349
  The *glob*-style matching is very simple. In most cases, you are best off using a real regular expression which will allow you to do more powerful matching and anchor matches to the beginning/end of the string etc.
345
350
 
346
351
 
347
- <a id="org14dee5e"></a>
352
+ <a id="orgc52d8a8"></a>
348
353
 
349
354
  ### exists(path) ==> boolean
350
355
 
@@ -380,7 +385,7 @@ Tests to see if remote file or directory exists. Returns type of remote object i
380
385
  ```
381
386
 
382
387
 
383
- <a id="orga0033c0"></a>
388
+ <a id="orgcfa8682"></a>
384
389
 
385
390
  ### stat(path) ==> object
386
391
 
@@ -431,7 +436,7 @@ Returns the attributes associated with the object pointed to by `path`.
431
436
  ```
432
437
 
433
438
 
434
- <a id="org02a3dc5"></a>
439
+ <a id="orgbe46842"></a>
435
440
 
436
441
  ### get(path, dst, options) ==> String|Stream|Buffer
437
442
 
@@ -487,7 +492,7 @@ In general, if you're going to pass in a string as the destination, you are bett
487
492
  - **Tip:** See examples file in the Git repository for more examples. You can pass any writeable stream in as the destination. For example, if you pass in `zlib.createGunzip()` writeable stream, you can both download and decompress a gzip file 'on the fly'.
488
493
 
489
494
 
490
- <a id="orge9f875d"></a>
495
+ <a id="org740cf5c"></a>
491
496
 
492
497
  ### fastGet(remotePath, localPath, options) ===> string
493
498
 
@@ -530,7 +535,7 @@ Downloads a file at remotePath to localPath using parallel reads for faster thro
530
535
  ```
531
536
 
532
537
 
533
- <a id="orgc7941ea"></a>
538
+ <a id="org429e96a"></a>
534
539
 
535
540
  ### put(src, remotePath, options) ==> string
536
541
 
@@ -580,7 +585,7 @@ Upload data from local system to remote server. If the `src` argument is a strin
580
585
  - **Tip:** If the src argument is a path string, consider just using `fastPut()`.
581
586
 
582
587
 
583
- <a id="org8f8794d"></a>
588
+ <a id="orgcab50c6"></a>
584
589
 
585
590
  ### fastPut(localPath, remotePath, options) ==> string
586
591
 
@@ -624,7 +629,7 @@ Uploads the data in file at `localPath` to a new file on remote server at `remot
624
629
  ```
625
630
 
626
631
 
627
- <a id="org82c75b5"></a>
632
+ <a id="orgc15d676"></a>
628
633
 
629
634
  ### append(input, remotePath, options) ==> string
630
635
 
@@ -668,7 +673,7 @@ Append the `input` data to an existing remote file. There is no integrity checki
668
673
  ```
669
674
 
670
675
 
671
- <a id="org42c5eeb"></a>
676
+ <a id="org6fab860"></a>
672
677
 
673
678
  ### mkdir(path, recursive) ==> string
674
679
 
@@ -696,7 +701,7 @@ Create a new directory. If the recursive flag is set to true, the method will cr
696
701
  ```
697
702
 
698
703
 
699
- <a id="orgd0aa59d"></a>
704
+ <a id="org520f6bc"></a>
700
705
 
701
706
  ### rmdir(path, recursive) ==> string
702
707
 
@@ -726,7 +731,7 @@ Remove a directory. If removing a directory and recursive flag is set to `true`,
726
731
  ```
727
732
 
728
733
 
729
- <a id="orgb496048"></a>
734
+ <a id="org1be8ca9"></a>
730
735
 
731
736
  ### delete(path, noErrorOK) ==> string
732
737
 
@@ -755,7 +760,7 @@ Delete a file on the remote server.
755
760
  ```
756
761
 
757
762
 
758
- <a id="org1a2be8f"></a>
763
+ <a id="org3d89131"></a>
759
764
 
760
765
  ### rename(fromPath, toPath) ==> string
761
766
 
@@ -784,7 +789,7 @@ Rename a file or directory from `fromPath` to `toPath`. You must have the necess
784
789
  ```
785
790
 
786
791
 
787
- <a id="org571c0b9"></a>
792
+ <a id="org58dfee5"></a>
788
793
 
789
794
  ### posixRename(fromPath, toPath) ==> string
790
795
 
@@ -811,7 +816,7 @@ client.connect(config)
811
816
  ```
812
817
 
813
818
 
814
- <a id="org02d64a4"></a>
819
+ <a id="orgb319965"></a>
815
820
 
816
821
  ### chmod(path, mode) ==> string
817
822
 
@@ -840,7 +845,7 @@ Change the mode (read, write or execute permissions) of a remote file or directo
840
845
  ```
841
846
 
842
847
 
843
- <a id="org008d567"></a>
848
+ <a id="orgf665476"></a>
844
849
 
845
850
  ### realPath(path) ===> string
846
851
 
@@ -851,14 +856,14 @@ Converts a relative path to an absolute path on the remote server. This method i
851
856
  - **path:** A file path, either relative or absolute. Can handle '.' and '..', but does not expand '~'.
852
857
 
853
858
 
854
- <a id="org7033d28"></a>
859
+ <a id="org409acd1"></a>
855
860
 
856
861
  ### cwd() ==> string
857
862
 
858
863
  Returns what the server believes is the current remote working directory.
859
864
 
860
865
 
861
- <a id="orgfa0102a"></a>
866
+ <a id="org668b085"></a>
862
867
 
863
868
  ### uploadDir(srcDir, dstDir, options) ==> string
864
869
 
@@ -927,7 +932,7 @@ The `useFastput` option is a boolean option. If `true`, the method will use the
927
932
  ```
928
933
 
929
934
 
930
- <a id="orgefe6fc6"></a>
935
+ <a id="org395ac4e"></a>
931
936
 
932
937
  ### downloadDir(srcDir, dstDir, options) ==> string
933
938
 
@@ -992,7 +997,7 @@ If the `useFastget` property is set to `true`, the method will use `fastGet()` t
992
997
  ```
993
998
 
994
999
 
995
- <a id="org783e363"></a>
1000
+ <a id="org8a73b83"></a>
996
1001
 
997
1002
  ### createReadStream(remotePath, options)) ==> stream object
998
1003
 
@@ -1009,7 +1014,7 @@ Returns a read stream object which is attached to the remote file specified by t
1009
1014
  - **end:** Postion to stop reading bytes (inclusive).
1010
1015
 
1011
1016
 
1012
- <a id="orgf45313d"></a>
1017
+ <a id="orgb71fb72"></a>
1013
1018
 
1014
1019
  ### createWriteStream(remotePath, options) ==> stream object
1015
1020
 
@@ -1024,7 +1029,7 @@ Returns a write stream object which is attached to the remote file specified in
1024
1029
  - **start:** Byte position to start writing from (inclusive). May require changing flag to 'r+'.
1025
1030
 
1026
1031
 
1027
- <a id="orga31c8c1"></a>
1032
+ <a id="org936f530"></a>
1028
1033
 
1029
1034
  ### rcopy(srcPath, dstPath) ==> string
1030
1035
 
@@ -1034,7 +1039,7 @@ Perfrom a remote file copy. The file identified by the `srcPath` argument will b
1034
1039
  - **dstPath:** Path to where the copy will be creaeted specified as a string
1035
1040
 
1036
1041
 
1037
- <a id="org4d02fde"></a>
1042
+ <a id="org62a8323"></a>
1038
1043
 
1039
1044
  ### end() ==> boolean
1040
1045
 
@@ -1058,7 +1063,7 @@ Ends the current client session, releasing the client socket and associated reso
1058
1063
  ```
1059
1064
 
1060
1065
 
1061
- <a id="orge5769d3"></a>
1066
+ <a id="orgd1ebc36"></a>
1062
1067
 
1063
1068
  ### Add and Remove Listeners
1064
1069
 
@@ -1079,12 +1084,12 @@ Although normally not required, you can add and remove custom listeners on the s
1079
1084
  Removes the specified listener from the event specified in eventType. Note that the `end()` method automatically removes all listeners from the client object.
1080
1085
 
1081
1086
 
1082
- <a id="org3e6ddf9"></a>
1087
+ <a id="orgdfff943"></a>
1083
1088
 
1084
1089
  # Platform Quirks & Warnings
1085
1090
 
1086
1091
 
1087
- <a id="org61f0fe5"></a>
1092
+ <a id="org886fe2e"></a>
1088
1093
 
1089
1094
  ## Server Capabilities
1090
1095
 
@@ -1093,7 +1098,16 @@ All SFTP servers and platforms are not equal. Some facilities provided by `ssh2-
1093
1098
  One way to determine whether an issue you are encountering is due to `ssh2-sftp-client` or due to the remote server or server platform is to use a simple CLI sftp program, such as openSSH's sftp command. If you observe the same behaviour using plain `sftp` on the command line, the issue is likely due to server or remote platform limitations. Note that you should not use a GUI sftp client, like `Filezilla` or `winSCP` as such GUI programs often attempt to hide these server and platform incompatibilities and will take additional steps to simulate missing functionality etc. You want to use a CLI program which does as little as possible.
1094
1099
 
1095
1100
 
1096
- <a id="orga7d6067"></a>
1101
+ <a id="org1719a52"></a>
1102
+
1103
+ ## Issues with `fastPut()` and `fastGet()` Methods
1104
+
1105
+ The `fastPut()` and `fastGet()` methods are known to be somewhat dependent on SFTP server capabilities. Some SFTP servers just do not work correctly with concurrent connections and some are known to have issues with negotiating packet sizes. These issues can sometimes be resolved by tweaking the options supplied to the methods, such as setting number of concurrent connections or a psecific packet size.
1106
+
1107
+ To see an example of the type of issues you can observe with `fastPut()` or `fastGet()`, have a look at [issue 407](https://github.com/theophilusx/ssh2-sftp-client/issues/407), which describes the experiences of one user. Bottom line, when it works, it tends to work well and be significantly faster than using just `get()` or `put()`. However, when developing code to run against different SFTP servers, especially where you are unable to test against each server, you are likely better off just using `get()` and `put()` or structuring your code so that users can select which method to use (this is what `ssh2-sftp-client` does - for example, see the `!downloadDir()` and `uploadDir()` methods.
1108
+
1109
+
1110
+ <a id="org42a51fc"></a>
1097
1111
 
1098
1112
  ## Promises, Events & Managing Exceptions
1099
1113
 
@@ -1112,14 +1126,14 @@ The other area where additional events are fired is during the end() call. To de
1112
1126
  In addition to the promise based event handlers, `ssh2-sftp-client` also implements global event handlers which will catch any `error`, `end` or `close` events. Essentially, these global handlers only reset the `sftp` property of the client object, effectively ensuring any subsequent calls are rejected and in the case of an error, send the error to the console.
1113
1127
 
1114
1128
 
1115
- <a id="orgc08d427"></a>
1129
+ <a id="orgd50a35a"></a>
1116
1130
 
1117
1131
  ### Adding Custom Handlers
1118
1132
 
1119
1133
  While the above strategies appear to work for the majority of use cases, there are always going to be edge cases which require more flexible or powerful event handling. To support this, the `on()` and `removeListener()` methods are provided. Any event listener added using the `on()` method will be added at the beginning of the list of handlers for that event, ensuring it will be called before any global or promise local events. See the documentation for the `on()` method for details.
1120
1134
 
1121
1135
 
1122
- <a id="org5439468"></a>
1136
+ <a id="org7b0987f"></a>
1123
1137
 
1124
1138
  ## Windows Based Servers
1125
1139
 
@@ -1128,7 +1142,7 @@ It appears that when the sftp server is running on Windows, a *ECONNRESET* error
1128
1142
  The best way to avoid this issue is to not re-use client objects. Always generate a new sftp client object for each new connection.
1129
1143
 
1130
1144
 
1131
- <a id="orgae9129c"></a>
1145
+ <a id="orgbe548c2"></a>
1132
1146
 
1133
1147
  ## Don't Re-use SftpClient Objects
1134
1148
 
@@ -1137,12 +1151,12 @@ Due to an issue with *ECONNRESET* error signals when connecting to Windows based
1137
1151
  To avoid this problem, don't re-use SftpClient objects. Generate a new SftpClient object for each connection. You can perform multiple actions with a single connection e.g. upload multiple files, download multiple files etc, but after you have called end(), you should not try to re-use the object with a further connect() call. Create a new object instead.
1138
1152
 
1139
1153
 
1140
- <a id="org3761660"></a>
1154
+ <a id="orgfddb94b"></a>
1141
1155
 
1142
1156
  # FAQ
1143
1157
 
1144
1158
 
1145
- <a id="org1e669d1"></a>
1159
+ <a id="orgbd2a31e"></a>
1146
1160
 
1147
1161
  ## Remote server drops connections with only an end event
1148
1162
 
@@ -1153,7 +1167,7 @@ Clients first make an unauthenticated connection to the SFTP server to begin neg
1153
1167
  One way to avoid this type of issue is to add a delay between connection attempts. It does not need to be a very long delay - just sufficient to permit the previous connection to be authenticated. In fact, the default setting for openSSH is `10:30:60`, so you really just need to have enough delay to ensure that the 1st connection has completed authentication before the 11th connection is attempted.
1154
1168
 
1155
1169
 
1156
- <a id="org71d5bab"></a>
1170
+ <a id="org9d72a61"></a>
1157
1171
 
1158
1172
  ## How can I pass writable stream as dst for get method?
1159
1173
 
@@ -1212,7 +1226,7 @@ sftp
1212
1226
  ```
1213
1227
 
1214
1228
 
1215
- <a id="orgaafc964"></a>
1229
+ <a id="org9fda086"></a>
1216
1230
 
1217
1231
  ## How can I upload files without having to specify a password?
1218
1232
 
@@ -1247,7 +1261,7 @@ sftp.connect({
1247
1261
  ```
1248
1262
 
1249
1263
 
1250
- <a id="orgebf85e2"></a>
1264
+ <a id="org2ccc5e8"></a>
1251
1265
 
1252
1266
  ## How can I connect through a Socks Proxy
1253
1267
 
@@ -1283,7 +1297,7 @@ client.connect({
1283
1297
  ```
1284
1298
 
1285
1299
 
1286
- <a id="org528d9ea"></a>
1300
+ <a id="org5306b6f"></a>
1287
1301
 
1288
1302
  ## Timeout while waiting for handshake or handshake errors
1289
1303
 
@@ -1292,7 +1306,7 @@ Some users have encountered the error 'Timeout while waiting for handshake' or '
1292
1306
  When encountering this type of problem, one worthwhile approach is to use openSSH's CLI sftp program with the `-v` switch to raise loggin levels. This will show you what algorithms the CLI is using. You can then use this information to match the names with the accepted algorithm names documented in the `ssh2` README to set the properties in the `algorithms` object.
1293
1307
 
1294
1308
 
1295
- <a id="org3b6ff20"></a>
1309
+ <a id="org3a77529"></a>
1296
1310
 
1297
1311
  ## How can I limit upload/download speed
1298
1312
 
@@ -1332,7 +1346,7 @@ try {
1332
1346
  ```
1333
1347
 
1334
1348
 
1335
- <a id="orgb5e285f"></a>
1349
+ <a id="org68eedc7"></a>
1336
1350
 
1337
1351
  ## Connection hangs or fails for larger files
1338
1352
 
@@ -1343,14 +1357,14 @@ A symptom of this issue is that you are able to upload small files, but uploadin
1343
1357
  For more explanation, see [issue #342](https://github.com/theophilusx/ssh2-sftp-client/issues/342).
1344
1358
 
1345
1359
 
1346
- <a id="org18ce0c2"></a>
1360
+ <a id="orgd436fa7"></a>
1347
1361
 
1348
1362
  # Examples
1349
1363
 
1350
1364
  I have started collecting example scripts in the example directory of the repository. These are mainly scripts I have put together in order to investigate issues or provide samples for users. They are not robust, lack adequate error handling and may contain errors. However, I think they are still useful for helping developers see how the module and API can be used.
1351
1365
 
1352
1366
 
1353
- <a id="orgf4b6c80"></a>
1367
+ <a id="orge21d870"></a>
1354
1368
 
1355
1369
  # Troubleshooting
1356
1370
 
@@ -1365,14 +1379,14 @@ Note also that in the repository there are two useful directories. The first is
1365
1379
  The second directory is the validation directory. I have some very simple scripts in this directory which perform basic tasks using only the `ssh2` modules (no `ssh2-sftp-client` module). These can be useful when trying to determine if the issue is with the underlying `ssh2` module or the `ssh2-sftp-client` wrapper module.
1366
1380
 
1367
1381
 
1368
- <a id="orga419582"></a>
1382
+ <a id="org287b86f"></a>
1369
1383
 
1370
1384
  ## Common Errors
1371
1385
 
1372
1386
  There are some common errors people tend to make when using Promises or Asyc/Await. These are by far the most common problem found in issues logged against this module. Please check for some of these before logging your issue.
1373
1387
 
1374
1388
 
1375
- <a id="orgd5f3557"></a>
1389
+ <a id="org20a99bb"></a>
1376
1390
 
1377
1391
  ### Not returning the promise in a `then()` block
1378
1392
 
@@ -1409,7 +1423,7 @@ Note the `return` statements. These ensure that the Promise returned by the clie
1409
1423
  A common symptom of this type of error is for file uploads or download to fail to complete or for data in those files to be truncated. What is happening is that the connection is being ended before the transfer has completed.
1410
1424
 
1411
1425
 
1412
- <a id="org557d1c5"></a>
1426
+ <a id="org51482b4"></a>
1413
1427
 
1414
1428
  ### Mixing Promise Chains and Async/Await
1415
1429
 
@@ -1469,7 +1483,7 @@ async function doSftp() {
1469
1483
  ```
1470
1484
 
1471
1485
 
1472
- <a id="org2bf9a3a"></a>
1486
+ <a id="orgb9a556a"></a>
1473
1487
 
1474
1488
  ### Try/catch and Error Handlers
1475
1489
 
@@ -1480,14 +1494,14 @@ The basic problem is that the try/catch block will have completed execution befo
1480
1494
  Error events are essentially asynchronous code. You don't know when such events will fire. Therefore, you cannot use a try/catch block to catch such event errors. Even creating an error handler which then throws an exception won't help as the key problem is that your try/catch block has already executed. There are a number of alternative ways to deal with this situation. However, the key symptom is that you see occasional uncaught error exceptions that cause your script to exit abnormally despite having try/catch blocks in your script. What you need to do is look at your code and find where errors are raised asynchronously and use an event handler or some other mechanism to manage any errors raised.
1481
1495
 
1482
1496
 
1483
- <a id="org89795d7"></a>
1497
+ <a id="org0d148f0"></a>
1484
1498
 
1485
1499
  ### Server Differences
1486
1500
 
1487
1501
  Not all SFTP servers are the same. Like most standards, the SFTP protocol has some level of interpretation and allows different levels of compliance. This means there can be differences in behaviour between different servers and code which works with one server will not work the same with another. For example, the value returned by *realpath* for non-existent objects can differ significantly. Some servers will throw an error for a particular operation while others will just return null, some servers support concurrent operations (such as used by fastGet/fastPut) while others will not and of course, the text of error messages can vary significantly. In particular, we have noticed significant differences across different platforms. It is therefore advisable to do comprehensive testing when the SFTP server is moved to a new platform. This includes moving from to a cloud based service even if the underlying platform remains the same. I have noticed that some cloud platforms can generate unexpected events, possibly related to additional functionality or features associated with the cloud implementation. For example, it appears SFTP servers running under Azure will generate an error event when the connection is closed even when the client has requested the connection be terminated. The same SFTP server running natively on Windows does not appear to exhibit such behaviour.
1488
1502
 
1489
1503
 
1490
- <a id="orgbec08b0"></a>
1504
+ <a id="orgf115391"></a>
1491
1505
 
1492
1506
  ### Avoid Concurrent Operations
1493
1507
 
@@ -1496,7 +1510,7 @@ Technically, SFTP should be able to perform multiple operations concurrently. As
1496
1510
  If you are going to try and perform concurrent operations, you need to test extensively and ensure you are using data which is large enough that context switching does occur (i.e. the request is not completed in a single run). Some SFTP servers will handle concurrent operations better than others.
1497
1511
 
1498
1512
 
1499
- <a id="org124cfc9"></a>
1513
+ <a id="orgc7c437f"></a>
1500
1514
 
1501
1515
  ## Debugging Support
1502
1516
 
@@ -1529,7 +1543,7 @@ If you just want to see debug messages from `ssh2-sftp-client` and exclude debug
1529
1543
  ```
1530
1544
 
1531
1545
 
1532
- <a id="org5f3c941"></a>
1546
+ <a id="orgc79ef28"></a>
1533
1547
 
1534
1548
  # Logging Issues
1535
1549
 
@@ -1546,7 +1560,7 @@ I am happy to try and help diagnose and fix any issues you encounter while using
1546
1560
  Perhaps the best assistance is a minimal reproducible example of the issue. Once the issue can be readily reproduced, it can usually be fixed very quickly.
1547
1561
 
1548
1562
 
1549
- <a id="org6e82efc"></a>
1563
+ <a id="org64bd2a2"></a>
1550
1564
 
1551
1565
  # Pull Requests
1552
1566
 
@@ -1561,7 +1575,7 @@ This module will adopt a standard semantic versioning policy. Please indicate in
1561
1575
  - **Bug Fix:** No change to functionality or features. Simple fix of an existing bug.
1562
1576
 
1563
1577
 
1564
- <a id="org680b5c2"></a>
1578
+ <a id="org709b0f9"></a>
1565
1579
 
1566
1580
  # Contributors
1567
1581
 
package/README.org CHANGED
@@ -9,13 +9,25 @@ convenience abstraction as well as a Promise based API.
9
9
  Documentation on the methods and available options in the underlying modules can
10
10
  be found on the [[https://github.com/mscdex/ssh2][SSH2]] project pages.
11
11
 
12
- Current stable release is *v9.0.1*.
12
+ Current stable release is *v9.0.2*.
13
13
 
14
14
  Code has been tested against Node versions 14.19.1, 16.15.0 and 18.1.0
15
15
 
16
16
  Node versions < 14.x are not supported.
17
17
 
18
18
  ** Version 9.x Changes
19
+ - Change the default end and close handlers not to throw error or reject
20
+ promises. Previously, an end or close event would cause an error to be raised or a
21
+ promise to be rejected if the event was deemed to be /unexpected/. However,
22
+ classification of events as being unexpected was unreliable and didn't add much real
23
+ value. Both these handlers will now invalidate the sftp connection object and log that
24
+ the event fired and nothing else.
25
+ - Changed when event handled flags are reset. Now they are reset after a new set of
26
+ temporary listeners are added.
27
+ - Don't throw an error when calling end() if there is no active sftp connection. It does
28
+ no harm to call end() when there is no connection, so no need to raise an error.
29
+ - Use nullish coalescing when setting retry parameters instead of or'ing with
30
+ defaults. Allows setting values to 0.
19
31
  - *Breaking Change*: This version uses syntax not supported in node versions
20
32
  prior to v14. Therefore, node versions less than v14 will not work.
21
33
  - *Breaking Change*: This ~list()~ method no longer accepts a regular expression
@@ -1077,7 +1089,6 @@ services.
1077
1089
 
1078
1090
  #+end_src
1079
1091
 
1080
-
1081
1092
  *** createReadStream(remotePath, options)) ==> stream object
1082
1093
 
1083
1094
  Returns a read stream object which is attached to the remote file specified by
@@ -1190,6 +1201,25 @@ the ~end()~ method automatically removes all listeners from the client object.
1190
1201
  additional steps to simulate missing functionality etc. You want to use a CLI
1191
1202
  program which does as little as possible.
1192
1203
 
1204
+ ** Issues with ~fastPut()~ and ~fastGet()~ Methods
1205
+
1206
+ The ~fastPut()~ and ~fastGet()~ methods are known to be somewhat dependent on
1207
+ SFTP server capabilities. Some SFTP servers just do not work correctly with
1208
+ concurrent connections and some are known to have issues with negotiating
1209
+ packet sizes. These issues can sometimes be resolved by tweaking the options
1210
+ supplied to the methods, such as setting number of concurrent connections or
1211
+ a psecific packet size.
1212
+
1213
+ To see an example of the type of issues you can observe with ~fastPut()~ or
1214
+ ~fastGet()~, have a look at [[https://github.com/theophilusx/ssh2-sftp-client/issues/407][issue 407]], which describes the experiences of one
1215
+ user. Bottom line, when it works, it tends to work well and be significantly
1216
+ faster than using just ~get()~ or ~put()~. However, when developing code to
1217
+ run against different SFTP servers, especially where you are unable to test
1218
+ against each server, you are likely better off just using ~get()~ and ~put()~
1219
+ or structuring your code so that users can select which method to use (this
1220
+ is what =ssh2-sftp-client= does - for example, see the ~!downloadDir()~ and
1221
+ ~uploadDir()~ methods.
1222
+
1193
1223
  ** Promises, Events & Managing Exceptions
1194
1224
 
1195
1225
  One of the challenges in providing a Promise based API over a module like
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ssh2-sftp-client",
3
- "version": "9.0.1",
3
+ "version": "9.0.2",
4
4
  "description": "ssh2 sftp client for node",
5
5
  "main": "src/index.js",
6
6
  "repository": {
package/src/index.js CHANGED
@@ -18,7 +18,7 @@ const { errorCode } = require('./constants');
18
18
 
19
19
  class SftpClient {
20
20
  constructor(clientName) {
21
- this.version = '9.0.0';
21
+ this.version = '9.0.2';
22
22
  this.client = new Client();
23
23
  this.sftp = undefined;
24
24
  this.clientName = clientName ? clientName : 'sftp';
@@ -31,7 +31,7 @@ class SftpClient {
31
31
  this.debug = undefined;
32
32
 
33
33
  this.client.on('close', () => {
34
- if (this.endCalled || this.closeHandled) {
34
+ if (this.endCalled || this.errorHandled || this.closeHandled) {
35
35
  // we are processing an expected end event or close event handled elsewhere
36
36
  this.debugMsg('Global: Ignoring handled close event');
37
37
  } else {
@@ -41,7 +41,7 @@ class SftpClient {
41
41
  });
42
42
 
43
43
  this.client.on('end', () => {
44
- if (this.endCalled || this.endHandled) {
44
+ if (this.endCalled || this.errorHandled || this.endHandled) {
45
45
  // end event expected or handled elsewhere
46
46
  this.debugMsg('Global: Ignoring hanlded end event');
47
47
  } else {
@@ -95,26 +95,20 @@ class SftpClient {
95
95
  } else {
96
96
  switch (err.code) {
97
97
  case 'ENOTFOUND':
98
- msg =
99
- `${name}: ${err.level} error. ` +
100
- `Address lookup failed for host ${err.hostname}${retry}`;
98
+ msg = `${name}: Address lookup failed for host${retry}`;
101
99
  break;
102
100
  case 'ECONNREFUSED':
103
- msg =
104
- `${name}: ${err.level} error. Remote host at ` +
105
- `${err.address} refused connection${retry}`;
101
+ msg = `${name}: Remote host refused connection${retry}`;
106
102
  break;
107
103
  case 'ECONNRESET':
108
- msg =
109
- `${name}: Remote host has reset the connection: ` +
110
- `${err.message}${retry}`;
104
+ msg = `${name}: Remote host has reset the connection: ${err.message}${retry}`;
111
105
  break;
112
106
  default:
113
107
  msg = `${name}: ${err.message}${retry}`;
114
108
  }
115
109
  code = err.code ? err.code : errorCode.generic;
116
110
  }
117
- let newError = new Error(msg);
111
+ const newError = new Error(msg);
118
112
  newError.code = code;
119
113
  newError.custom = true;
120
114
  this.debugMsg(`${newError.message} (${newError.code})`);
@@ -159,9 +153,7 @@ class SftpClient {
159
153
  return new Promise((resolve, reject) => {
160
154
  listeners = addTempListeners(this, 'getConnection', reject);
161
155
  doReady = () => {
162
- this.debugMsg(
163
- 'getConnection ready listener: got connection - promise resolved'
164
- );
156
+ this.debugMsg('getConnection ready listener: got connection - promise resolved');
165
157
  resolve(true);
166
158
  };
167
159
  this.on('ready', doReady);
@@ -169,7 +161,6 @@ class SftpClient {
169
161
  }).finally(() => {
170
162
  this.removeListener('ready', doReady);
171
163
  removeTempListeners(this, listeners, 'getConnection');
172
- this._resetEventFlags();
173
164
  });
174
165
  }
175
166
 
@@ -177,7 +168,6 @@ class SftpClient {
177
168
  return new Promise((resolve, reject) => {
178
169
  this.client.sftp((err, sftp) => {
179
170
  if (err) {
180
- this.client.end();
181
171
  reject(this.fmtError(err, 'getSftpChannel', err.code));
182
172
  } else {
183
173
  this.debugMsg('getSftpChannel: SFTP channel established');
@@ -208,10 +198,7 @@ class SftpClient {
208
198
  if (config.debug) {
209
199
  this.debug = config.debug;
210
200
  this.debugMsg('connect: Debugging turned on');
211
- this.debugMsg(
212
- `ssh2-sftp-client Version: ${this.version} `,
213
- process.versions
214
- );
201
+ this.debugMsg(`ssh2-sftp-client Version: ${this.version} `, process.versions);
215
202
  }
216
203
  if (this.sftp) {
217
204
  throw this.fmtError(
@@ -220,10 +207,10 @@ class SftpClient {
220
207
  errorCode.connect
221
208
  );
222
209
  }
223
- let retryOpts = {
224
- retries: config.retries || 1,
225
- factor: config.factor || 2,
226
- minTimeout: config.retry_minTimeout || 25000,
210
+ const retryOpts = {
211
+ retries: config.retries ?? 1,
212
+ factor: config.factor ?? 2,
213
+ minTimeout: config.retry_minTimeout ?? 25000,
227
214
  };
228
215
  await promiseRetry(retryOpts, async (retry, attempt) => {
229
216
  try {
@@ -234,35 +221,26 @@ class SftpClient {
234
221
  case 'ENOTFOUND':
235
222
  case 'ECONNREFUSED':
236
223
  case 'ERR_SOCKET_BAD_PORT':
237
- throw err;
238
- case undefined: {
239
- if (
240
- err.message.endsWith(
241
- 'All configured authentication methods failed'
242
- )
243
- ) {
244
- throw this.fmtError(
245
- err.message,
246
- 'getConnection',
247
- errorCode.badAuth
248
- );
249
- }
250
- retry(err);
251
- break;
224
+ throw err;
225
+ case undefined: {
226
+ if (err.message.endsWith('All configured authentication methods failed')) {
227
+ throw this.fmtError(err.message, 'getConnection', errorCode.badAuth);
252
228
  }
253
- default:
254
- retry(err);
229
+ retry(err);
230
+ break;
231
+ }
232
+ default:
233
+ retry(err);
255
234
  }
256
235
  }
257
236
  });
258
- let sftp = await this.getSftpChannel();
237
+ const sftp = await this.getSftpChannel();
259
238
  return sftp;
260
239
  } catch (err) {
261
- this.end();
240
+ await this.end();
262
241
  throw err.custom ? err : this.fmtError(err, 'connect');
263
242
  } finally {
264
243
  removeTempListeners(this, listeners, 'connect');
265
- this._resetEventFlags();
266
244
  }
267
245
  }
268
246
 
@@ -286,9 +264,7 @@ class SftpClient {
286
264
  this.debugMsg('_realPath <- ""');
287
265
  resolve('');
288
266
  } else {
289
- reject(
290
- this.fmtError(`${err.message} ${rPath}`, 'realPath', err.code)
291
- );
267
+ reject(this.fmtError(`${err.message} ${rPath}`, 'realPath', err.code));
292
268
  }
293
269
  }
294
270
  this.debugMsg(`_realPath <- ${absPath}`);
@@ -309,7 +285,6 @@ class SftpClient {
309
285
  : this.fmtError(`${e.message} ${remotePath}`, 'realPath', e.code);
310
286
  } finally {
311
287
  removeTempListeners(this, listeners, 'realPath');
312
- this._resetEventFlags();
313
288
  }
314
289
  }
315
290
 
@@ -336,13 +311,7 @@ class SftpClient {
336
311
  this.sftp.stat(aPath, (err, stats) => {
337
312
  if (err) {
338
313
  if (err.code === 2 || err.code === 4) {
339
- reject(
340
- this.fmtError(
341
- `No such file: ${aPath}`,
342
- '_stat',
343
- errorCode.notexist
344
- )
345
- );
314
+ reject(this.fmtError(`No such file: ${aPath}`, '_stat', errorCode.notexist));
346
315
  } else {
347
316
  reject(this.fmtError(`${err.message} ${aPath}`, '_stat', err.code));
348
317
  }
@@ -380,7 +349,6 @@ class SftpClient {
380
349
  throw err.custom ? err : this.fmtError(err, 'stat', err.code);
381
350
  } finally {
382
351
  removeTempListeners(this, listeners, 'stat');
383
- this._resetEventFlags();
384
352
  }
385
353
  }
386
354
 
@@ -437,7 +405,6 @@ class SftpClient {
437
405
  throw err.custom ? err : this.fmtError(err, 'exists', err.code);
438
406
  } finally {
439
407
  removeTempListeners(this, listeners, 'exists');
440
- this._resetEventFlags();
441
408
  }
442
409
  }
443
410
 
@@ -458,9 +425,7 @@ class SftpClient {
458
425
  return new Promise((resolve, reject) => {
459
426
  this.sftp.readdir(remotePath, (err, fileList) => {
460
427
  if (err) {
461
- reject(
462
- this.fmtError(`${err.message} ${remotePath}`, 'list', err.code)
463
- );
428
+ reject(this.fmtError(`${err.message} ${remotePath}`, 'list', err.code));
464
429
  } else {
465
430
  const reg = /-/gi;
466
431
  const newList = fileList.map((item) => {
@@ -497,12 +462,9 @@ class SftpClient {
497
462
  haveConnection(this, 'list');
498
463
  return await this._list(remotePath, filter);
499
464
  } catch (e) {
500
- throw e.custom
501
- ? e
502
- : this.fmtError(`${e.message} ${remotePath}`, 'list', e.code);
465
+ throw e.custom ? e : this.fmtError(`${e.message} ${remotePath}`, 'list', e.code);
503
466
  } finally {
504
467
  removeTempListeners(this, listeners, 'list');
505
- this._resetEventFlags();
506
468
  }
507
469
  }
508
470
 
@@ -593,12 +555,9 @@ class SftpClient {
593
555
  haveConnection(this, 'get');
594
556
  return await this._get(remotePath, dst, options);
595
557
  } catch (e) {
596
- throw e.custom
597
- ? e
598
- : this.fmtError(`${e.message} ${remotePath}`, 'get', e.code);
558
+ throw e.custom ? e : this.fmtError(`${e.message} ${remotePath}`, 'get', e.code);
599
559
  } finally {
600
560
  removeTempListeners(this, listeners, 'get');
601
- this._resetEventFlags();
602
561
  }
603
562
  }
604
563
 
@@ -616,9 +575,7 @@ class SftpClient {
616
575
  return new Promise((resolve, reject) => {
617
576
  this.sftp.fastGet(rPath, lPath, opts, (err) => {
618
577
  if (err) {
619
- reject(
620
- this.fmtError(`${err.message} Remote: ${rPath} Local: ${lPath}`)
621
- );
578
+ reject(this.fmtError(`${err.message} Remote: ${rPath} Local: ${lPath}`));
622
579
  }
623
580
  resolve(`${rPath} was successfully download to ${lPath}!`);
624
581
  });
@@ -632,9 +589,7 @@ class SftpClient {
632
589
  haveConnection(this, 'fastGet');
633
590
  const ftype = await this.exists(remotePath);
634
591
  if (ftype !== '-') {
635
- const msg = `${
636
- !ftype ? 'No such file ' : 'Not a regular file'
637
- } ${remotePath}`;
592
+ const msg = `${!ftype ? 'No such file ' : 'Not a regular file'} ${remotePath}`;
638
593
  throw this.fmtError(msg, 'fastGet', errorCode.badPath);
639
594
  }
640
595
  const localCheck = haveLocalCreate(localPath);
@@ -650,7 +605,6 @@ class SftpClient {
650
605
  throw this.fmtError(err, 'fastGet');
651
606
  } finally {
652
607
  removeTempListeners(this, listeners, 'fastGet');
653
- this._resetEventFlags();
654
608
  }
655
609
  }
656
610
 
@@ -709,7 +663,6 @@ class SftpClient {
709
663
  throw e.custom ? e : this.fmtError(e.message, 'fastPut', e.code);
710
664
  } finally {
711
665
  removeTempListeners(this, listeners, 'fastPut');
712
- this._resetEventFlags();
713
666
  }
714
667
  }
715
668
 
@@ -757,9 +710,7 @@ class SftpClient {
757
710
  rdr.once('error', (err) => {
758
711
  reject(
759
712
  this.fmtError(
760
- `${err.message} ${
761
- typeof lPath === 'string' ? lPath : '<stream>'
762
- }`,
713
+ `${err.message} ${typeof lPath === 'string' ? lPath : '<stream>'}`,
763
714
  '_put',
764
715
  err.code
765
716
  )
@@ -790,7 +741,6 @@ class SftpClient {
790
741
  throw e.custom ? e : this.fmtError(e.message, 'put', e.code);
791
742
  } finally {
792
743
  removeTempListeners(this, listeners, 'put');
793
- this._resetEventFlags();
794
744
  }
795
745
  }
796
746
 
@@ -847,7 +797,6 @@ class SftpClient {
847
797
  throw e.custom ? e : this.fmtError(e.message, 'append', e.code);
848
798
  } finally {
849
799
  removeTempListeners(this, listeners, 'append');
850
- this._resetEventFlags();
851
800
  }
852
801
  }
853
802
 
@@ -938,7 +887,6 @@ class SftpClient {
938
887
  throw this.fmtError(`${err.message}`, 'mkdir', err.code);
939
888
  } finally {
940
889
  removeTempListeners(this, listeners, 'append');
941
- this._resetEventFlags();
942
890
  }
943
891
  }
944
892
 
@@ -979,9 +927,7 @@ class SftpClient {
979
927
  }
980
928
  const promiseList = [];
981
929
  for (const f of files) {
982
- promiseList.push(
983
- this._delete(`${p}${this.remotePathSep}${f.name}`)
984
- );
930
+ promiseList.push(this._delete(`${p}${this.remotePathSep}${f.name}`));
985
931
  }
986
932
  await Promise.all(promiseList);
987
933
  }
@@ -1017,7 +963,6 @@ class SftpClient {
1017
963
  throw err.custom ? err : this.fmtError(err.message, 'rmdir', err.code);
1018
964
  } finally {
1019
965
  removeTempListeners(this, listeners, 'rmdir');
1020
- this._resetEventFlags();
1021
966
  }
1022
967
  }
1023
968
 
@@ -1039,9 +984,7 @@ class SftpClient {
1039
984
  if (notFoundOK && err.code === 2) {
1040
985
  resolve(`Successfully deleted ${rPath}`);
1041
986
  } else {
1042
- reject(
1043
- this.fmtError(`${err.message} ${rPath}`, 'delete', err.code)
1044
- );
987
+ reject(this.fmtError(`${err.message} ${rPath}`, 'delete', err.code));
1045
988
  }
1046
989
  }
1047
990
  resolve(`Successfully deleted ${rPath}`);
@@ -1059,7 +1002,6 @@ class SftpClient {
1059
1002
  throw err.custom ? err : this.fmtError(err.message, 'delete', err.code);
1060
1003
  } finally {
1061
1004
  removeTempListeners(this, listeners, 'delete');
1062
- this._resetEventFlags();
1063
1005
  }
1064
1006
  }
1065
1007
 
@@ -1100,14 +1042,9 @@ class SftpClient {
1100
1042
  } catch (err) {
1101
1043
  throw err.custom
1102
1044
  ? err
1103
- : this.fmtError(
1104
- `${err.message} ${fromPath} ${toPath}`,
1105
- 'rename',
1106
- err.code
1107
- );
1045
+ : this.fmtError(`${err.message} ${fromPath} ${toPath}`, 'rename', err.code);
1108
1046
  } finally {
1109
1047
  removeTempListeners(this, listeners, 'rename');
1110
- this._resetEventFlags();
1111
1048
  }
1112
1049
  }
1113
1050
 
@@ -1149,14 +1086,9 @@ class SftpClient {
1149
1086
  } catch (err) {
1150
1087
  throw err.custom
1151
1088
  ? err
1152
- : this.fmtError(
1153
- `${err.message} ${fromPath} ${toPath}`,
1154
- 'posixRename',
1155
- err.code
1156
- );
1089
+ : this.fmtError(`${err.message} ${fromPath} ${toPath}`, 'posixRename', err.code);
1157
1090
  } finally {
1158
1091
  removeTempListeners(this, listeners, 'posixRename');
1159
- this._resetEventFlags();
1160
1092
  }
1161
1093
  }
1162
1094
 
@@ -1193,7 +1125,6 @@ class SftpClient {
1193
1125
  : this.fmtError(`${err.message} ${remotePath}`, 'chmod', err.code);
1194
1126
  } finally {
1195
1127
  removeTempListeners(this, listeners, 'chmod');
1196
- this._resetEventFlags();
1197
1128
  }
1198
1129
  }
1199
1130
 
@@ -1268,9 +1199,7 @@ class SftpClient {
1268
1199
  }
1269
1200
  this.client.emit('upload', { source: newSrc, destination: newDst });
1270
1201
  } else {
1271
- this.debugMsg(
1272
- `uploadDir: File ignored: ${e.name} not a regular file`
1273
- );
1202
+ this.debugMsg(`uploadDir: File ignored: ${e.name} not a regular file`);
1274
1203
  }
1275
1204
  await Promise.all(fileUploads);
1276
1205
  }
@@ -1293,7 +1222,6 @@ class SftpClient {
1293
1222
  throw err.custom ? err : this.fmtError(err, 'uploadDir');
1294
1223
  } finally {
1295
1224
  removeTempListeners(this, listeners, 'chmod');
1296
- this._resetEventFlags();
1297
1225
  }
1298
1226
  }
1299
1227
 
@@ -1355,9 +1283,7 @@ class SftpClient {
1355
1283
  }
1356
1284
  this.client.emit('download', { source: newSrc, destination: newDst });
1357
1285
  } else {
1358
- this.debugMsg(
1359
- `downloadDir: File ignored: ${f.name} not regular file`
1360
- );
1286
+ this.debugMsg(`downloadDir: File ignored: ${f.name} not regular file`);
1361
1287
  }
1362
1288
  }
1363
1289
  await Promise.all(downloadFiles);
@@ -1379,7 +1305,6 @@ class SftpClient {
1379
1305
  throw err.custom ? err : this.fmtError(err, 'downloadDir', err.code);
1380
1306
  } finally {
1381
1307
  removeTempListeners(this, listeners, 'downloadDir');
1382
- this._resetEventFlags();
1383
1308
  }
1384
1309
  }
1385
1310
 
@@ -1404,12 +1329,9 @@ class SftpClient {
1404
1329
  const stream = this.sftp.createReadStream(remotePath, options);
1405
1330
  return stream;
1406
1331
  } catch (err) {
1407
- throw err.custom
1408
- ? err
1409
- : this.fmtError(err.message, 'createReadStream', err.code);
1332
+ throw err.custom ? err : this.fmtError(err.message, 'createReadStream', err.code);
1410
1333
  } finally {
1411
1334
  removeTempListeners(this, listeners, 'createReadStreame');
1412
- this._resetEventFlags();
1413
1335
  }
1414
1336
  }
1415
1337
 
@@ -1434,12 +1356,9 @@ class SftpClient {
1434
1356
  const stream = this.sftp.createWriteStream(remotePath, options);
1435
1357
  return stream;
1436
1358
  } catch (err) {
1437
- throw err.custom
1438
- ? err
1439
- : this.fmtError(err.message, 'createWriteStream', err.code);
1359
+ throw err.custom ? err : this.fmtError(err.message, 'createWriteStream', err.code);
1440
1360
  } finally {
1441
1361
  removeTempListeners(this, listeners, 'createWriteStream');
1442
- this._resetEventFlags();
1443
1362
  }
1444
1363
  }
1445
1364
 
@@ -1488,11 +1407,7 @@ class SftpClient {
1488
1407
  );
1489
1408
  }
1490
1409
  if (srcExists !== '-') {
1491
- throw this.fmtError(
1492
- `Source not a file ${srcPath}`,
1493
- 'rcopy',
1494
- errorCode.badPath
1495
- );
1410
+ throw this.fmtError(`Source not a file ${srcPath}`, 'rcopy', errorCode.badPath);
1496
1411
  }
1497
1412
  const dstPath = await normalizeRemotePath(this, dst);
1498
1413
  const dstExists = await this.exists(dstPath);
@@ -1503,12 +1418,11 @@ class SftpClient {
1503
1418
  errorCode.badPath
1504
1419
  );
1505
1420
  }
1506
- return await this._rcopy(srcPath, dstPath);
1421
+ return this._rcopy(srcPath, dstPath);
1507
1422
  } catch (err) {
1508
1423
  throw err.custom ? err : this.fmtError(err, 'rcopy');
1509
1424
  } finally {
1510
1425
  removeTempListeners(this, listeners, 'rcopy');
1511
- this._resetEventFlags();
1512
1426
  }
1513
1427
  }
1514
1428
  /**
@@ -1529,14 +1443,17 @@ class SftpClient {
1529
1443
  resolve(true);
1530
1444
  };
1531
1445
  this.on('close', endCloseHandler);
1532
- if (haveConnection(this, 'end', reject)) {
1446
+ if (this.client) {
1533
1447
  this.client.end();
1448
+ } else {
1449
+ // no actual connection exists - just resolve
1450
+ this.debugMsg('end: Called when no connection active');
1451
+ resolve(true);
1534
1452
  }
1535
1453
  }).finally(() => {
1536
1454
  removeTempListeners(this, listeners, 'end');
1537
1455
  this.removeListener('close', endCloseHandler);
1538
1456
  this.endCalled = false;
1539
- this._resetEventFlags();
1540
1457
  });
1541
1458
  }
1542
1459
  }
package/src/utils.js CHANGED
@@ -10,13 +10,14 @@ const { errorCode } = require('./constants');
10
10
  * @throws {Error} Throws new error
11
11
  */
12
12
  function errorListener(client, name, reject) {
13
- let fn = (err) => {
13
+ const fn = (err) => {
14
14
  if (client.endCalled || client.errorHandled) {
15
15
  // error already handled or expected - ignore
16
+ client.debugMsg(`${name} errorListener - ignoring handled error`);
16
17
  return;
17
18
  }
18
19
  client.errorHandled = true;
19
- let newError = new Error(`${name}: ${err.message}`);
20
+ const newError = new Error(`${name}: ${err.message}`);
20
21
  newError.code = err.code;
21
22
  if (reject) {
22
23
  reject(newError);
@@ -28,43 +29,56 @@ function errorListener(client, name, reject) {
28
29
  }
29
30
 
30
31
  function endListener(client, name, reject) {
31
- let fn = function () {
32
- if (client.endCalled || client.endHandled) {
32
+ const fn = function () {
33
+ client.sftp = undefined;
34
+ if (client.endCalled || client.endHandled || client.errorHandled) {
33
35
  // end event already handled - ignore
36
+ client.debugMsg(`${name} endListener - ignoring handled error`);
34
37
  return;
35
38
  }
36
- client.sftp = undefined;
37
39
  client.endHandled = true;
38
- let err = new Error(`${name} Unexpected end event raised`);
39
- if (reject) {
40
- reject(err);
41
- } else {
42
- throw err;
43
- }
40
+ client.debugMsg(`${name} Unexpected end event - ignoring`);
41
+ // Don't reject/throw error, just log it and move on
42
+ // after invalidating the connection
43
+ // const err = new Error(`${name} Unexpected end event raised`);
44
+ // if (reject) {
45
+ // reject(err);
46
+ // } else {
47
+ // throw err;
48
+ // }
44
49
  };
45
50
  return fn;
46
51
  }
47
52
 
48
53
  function closeListener(client, name, reject) {
49
- let fn = function () {
50
- if (client.endCalled || client.closeHandled) {
54
+ const fn = function () {
55
+ client.sftp = undefined;
56
+ if (
57
+ client.endCalled ||
58
+ client.closeHandled ||
59
+ client.errorHandled ||
60
+ client.endHandled
61
+ ) {
51
62
  // handled or expected close event - ignore
63
+ client.debugMsg(`${name} closeListener - ignoring handled error`);
52
64
  return;
53
65
  }
54
- client.sftp = undefined;
55
66
  client.closeHandled = true;
56
- let err = new Error(`${name}: Unexpected close event raised`);
57
- if (reject) {
58
- reject(err);
59
- } else {
60
- throw err;
61
- }
67
+ client.debugMsg(`${name} Unexpected close event raised - ignoring`);
68
+ // Don't throw/reject on close events. Just invalidate the connection
69
+ // and move on.
70
+ // const err = new Error(`${name}: Unexpected close event raised`);
71
+ // if (reject) {
72
+ // reject(err);
73
+ // } else {
74
+ // throw err;
75
+ // }
62
76
  };
63
77
  return fn;
64
78
  }
65
79
 
66
80
  function addTempListeners(client, name, reject) {
67
- let listeners = {
81
+ const listeners = {
68
82
  end: endListener(client, name, reject),
69
83
  close: closeListener(client, name, reject),
70
84
  error: errorListener(client, name, reject),
@@ -72,6 +86,7 @@ function addTempListeners(client, name, reject) {
72
86
  client.on('end', listeners.end);
73
87
  client.on('close', listeners.close);
74
88
  client.on('error', listeners.error);
89
+ client._resetEventFlags();
75
90
  return listeners;
76
91
  }
77
92
 
@@ -106,9 +121,7 @@ function localExists(filePath) {
106
121
  } else if (stats.isFile()) {
107
122
  return '-';
108
123
  } else {
109
- let err = new Error(
110
- `Bad path: ${filePath}: target must be a file or directory`
111
- );
124
+ const err = new Error(`Bad path: ${filePath}: target must be a file or directory`);
112
125
  err.code = errorCode.badPath;
113
126
  throw err;
114
127
  }
@@ -249,7 +262,7 @@ async function normalizeRemotePath(client, aPath) {
249
262
  */
250
263
  function haveConnection(client, name, reject) {
251
264
  if (!client.sftp) {
252
- let newError = new Error(`${name}: No SFTP connection available`);
265
+ const newError = new Error(`${name}: No SFTP connection available`);
253
266
  newError.code = errorCode.connect;
254
267
  if (reject) {
255
268
  reject(newError);