ssh2-sftp-client 7.2.3 → 8.0.0

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,58 +1,58 @@
1
1
  - [Overview](#sec-1)
2
+ - [Version 8.x.x Changes](#sec-1-1)
2
3
  - [Installation](#sec-2)
3
4
  - [Basic Usage](#sec-3)
4
- - [Version 7.x Changes](#sec-4)
5
- - [Documentation](#sec-5)
6
- - [Specifying Paths](#sec-5-1)
7
- - [Methods](#sec-5-2)
8
- - [new SftpClient(name) ===> SFTP client object](#sec-5-2-1)
9
- - [connect(config) ===> SFTP object](#sec-5-2-2)
10
- - [list(path, pattern) ==> Array[object]](#sec-5-2-3)
11
- - [exists(path) ==> boolean](#sec-5-2-4)
12
- - [stat(path) ==> object](#sec-5-2-5)
13
- - [get(path, dst, options) ==> String|Stream|Buffer](#sec-5-2-6)
14
- - [fastGet(remotePath, localPath, options) ===> string](#sec-5-2-7)
15
- - [put(src, remotePath, options) ==> string](#sec-5-2-8)
16
- - [fastPut(localPath, remotePath, options) ==> string](#sec-5-2-9)
17
- - [append(input, remotePath, options) ==> string](#sec-5-2-10)
18
- - [mkdir(path, recursive) ==> string](#sec-5-2-11)
19
- - [rmdir(path, recursive) ==> string](#sec-5-2-12)
20
- - [delete(path, noErrorOK) ==> string](#sec-5-2-13)
21
- - [rename(fromPath, toPath) ==> string](#sec-5-2-14)
22
- - [posixRename(fromPath, toPath) ==> string](#sec-5-2-15)
23
- - [chmod(path, mode) ==> string](#sec-5-2-16)
24
- - [realPath(path) ===> string](#sec-5-2-17)
25
- - [cwd() ==> string](#sec-5-2-18)
26
- - [uploadDir(srcDir, dstDir, filter) ==> string](#sec-5-2-19)
27
- - [downloadDir(srcDir, dstDir, filter) ==> string](#sec-5-2-20)
28
- - [end() ==> boolean](#sec-5-2-21)
29
- - [Add and Remove Listeners](#sec-5-2-22)
30
- - [Platform Quirks & Warnings](#sec-6)
31
- - [Server Capabilities](#sec-6-1)
32
- - [Promises, Events & Managing Exceptions](#sec-6-2)
33
- - [Adding Custom Handlers](#sec-6-2-1)
34
- - [Windows Based Servers](#sec-6-3)
35
- - [Don't Re-use SftpClient Objects](#sec-6-4)
36
- - [FAQ](#sec-7)
37
- - [Remote server drops connections with only an end event](#sec-7-1)
38
- - [How can I pass writable stream as dst for get method?](#sec-7-2)
39
- - [How can I upload files without having to specify a password?](#sec-7-3)
40
- - [How can I connect through a Socks Proxy](#sec-7-4)
41
- - [Timeout while waiting for handshake or handshake errors](#sec-7-5)
42
- - [How can I limit upload/download speed](#sec-7-6)
43
- - [Connection hangs or fails for larger files](#sec-7-7)
44
- - [Examples](#sec-8)
45
- - [Troubleshooting](#sec-9)
46
- - [Common Errors](#sec-9-1)
47
- - [Not returning the promise in a `then()` block](#sec-9-1-1)
48
- - [Mixing Promise Chains and Async/Await](#sec-9-1-2)
49
- - [Try/catch and Error Handlers](#sec-9-1-3)
50
- - [Server Differences](#sec-9-1-4)
51
- - [Avoid Concurrent Operations](#sec-9-1-5)
52
- - [Debugging Support](#sec-9-2)
53
- - [Logging Issues](#sec-10)
54
- - [Pull Requests](#sec-11)
55
- - [Contributors](#sec-12)
5
+ - [Documentation](#sec-4)
6
+ - [Specifying Paths](#sec-4-1)
7
+ - [Methods](#sec-4-2)
8
+ - [new SftpClient(name) ===> SFTP client object](#sec-4-2-1)
9
+ - [connect(config) ===> SFTP object](#sec-4-2-2)
10
+ - [list(path, pattern) ==> Array[object]](#sec-4-2-3)
11
+ - [exists(path) ==> boolean](#sec-4-2-4)
12
+ - [stat(path) ==> object](#sec-4-2-5)
13
+ - [get(path, dst, options) ==> String|Stream|Buffer](#sec-4-2-6)
14
+ - [fastGet(remotePath, localPath, options) ===> string](#sec-4-2-7)
15
+ - [put(src, remotePath, options) ==> string](#sec-4-2-8)
16
+ - [fastPut(localPath, remotePath, options) ==> string](#sec-4-2-9)
17
+ - [append(input, remotePath, options) ==> string](#sec-4-2-10)
18
+ - [mkdir(path, recursive) ==> string](#sec-4-2-11)
19
+ - [rmdir(path, recursive) ==> string](#sec-4-2-12)
20
+ - [delete(path, noErrorOK) ==> string](#sec-4-2-13)
21
+ - [rename(fromPath, toPath) ==> string](#sec-4-2-14)
22
+ - [posixRename(fromPath, toPath) ==> string](#sec-4-2-15)
23
+ - [chmod(path, mode) ==> string](#sec-4-2-16)
24
+ - [realPath(path) ===> string](#sec-4-2-17)
25
+ - [cwd() ==> string](#sec-4-2-18)
26
+ - [uploadDir(srcDir, dstDir, filter) ==> string](#sec-4-2-19)
27
+ - [downloadDir(srcDir, dstDir, filter) ==> string](#sec-4-2-20)
28
+ - [end() ==> boolean](#sec-4-2-21)
29
+ - [Add and Remove Listeners](#sec-4-2-22)
30
+ - [Platform Quirks & Warnings](#sec-5)
31
+ - [Server Capabilities](#sec-5-1)
32
+ - [Promises, Events & Managing Exceptions](#sec-5-2)
33
+ - [Adding Custom Handlers](#sec-5-2-1)
34
+ - [Windows Based Servers](#sec-5-3)
35
+ - [Don't Re-use SftpClient Objects](#sec-5-4)
36
+ - [FAQ](#sec-6)
37
+ - [Remote server drops connections with only an end event](#sec-6-1)
38
+ - [How can I pass writable stream as dst for get method?](#sec-6-2)
39
+ - [How can I upload files without having to specify a password?](#sec-6-3)
40
+ - [How can I connect through a Socks Proxy](#sec-6-4)
41
+ - [Timeout while waiting for handshake or handshake errors](#sec-6-5)
42
+ - [How can I limit upload/download speed](#sec-6-6)
43
+ - [Connection hangs or fails for larger files](#sec-6-7)
44
+ - [Examples](#sec-7)
45
+ - [Troubleshooting](#sec-8)
46
+ - [Common Errors](#sec-8-1)
47
+ - [Not returning the promise in a `then()` block](#sec-8-1-1)
48
+ - [Mixing Promise Chains and Async/Await](#sec-8-1-2)
49
+ - [Try/catch and Error Handlers](#sec-8-1-3)
50
+ - [Server Differences](#sec-8-1-4)
51
+ - [Avoid Concurrent Operations](#sec-8-1-5)
52
+ - [Debugging Support](#sec-8-2)
53
+ - [Logging Issues](#sec-9)
54
+ - [Pull Requests](#sec-10)
55
+ - [Contributors](#sec-11)
56
56
 
57
57
 
58
58
  # Overview<a id="sec-1"></a>
@@ -61,12 +61,18 @@ an SFTP client for node.js, a wrapper around [SSH2](https://github.com/mscdex/ss
61
61
 
62
62
  Documentation on the methods and available options in the underlying modules can be found on the [SSH2](https://github.com/mscdex/ssh2) project pages.
63
63
 
64
- Current stable release is **v7.2.3**.
64
+ Current stable release is **v8.0.0**.
65
65
 
66
66
  Code has been tested against Node versions 14.19.1, 16.14.2 and 17.8.0
67
67
 
68
68
  Node versions < 12.x are not supported. However, node v10.x should still work, although some tests will fail due to changes in file system functions used in test setup and tear down.
69
69
 
70
+ ## Version 8.x.x Changes<a id="sec-1-1"></a>
71
+
72
+ - **Breaking Change**: The API for `uploadDir()` and `downloadDir()` has been changed. These methods now expect a function as the optional 3rd argument. Previously, the 3rd argument was a regular expression used to filter out which files and directories should be included in the upload or download action. The method now expects a predicate function which will return true if the target is to be included in the upload or download and false if it is to be excluded. The predicate function will be called with two arguments, a full path to the target object and a boolean value which is true when the target is a directory, false otherwise. If no filter predicate is supplied, all files and directories under the initial target directory will be transferred. At this time, asynchronous filter functions are not supported.
73
+
74
+ - Internal Change: The `rmdir()` method has been refactored to enable asynchronous deletion of files and sub-directories. This has significantly increased performance when deleting larger directory trees, especially trees which are *broad* with lots of files and directories at the same level. For deep narrow trees, there is less performance benefit because sub-directories must be removed before parents, which imposes synchronous processing. It is likely that for extremely large directory trees, the additional resources required to run large numbers of asynchronous tasks will become problematic. In such situations, it may be necessary to manually break up the deletion process into multiple `rmdir()` calls. However, this is considered a fairly extreme use case which is rare (a use case which wold also have been problematic with the old implementation as performance would have been very poor).
75
+
70
76
  # Installation<a id="sec-2"></a>
71
77
 
72
78
  ```shell
@@ -93,25 +99,13 @@ sftp.connect({
93
99
  });
94
100
  ```
95
101
 
96
- # Version 7.x Changes<a id="sec-4"></a>
97
-
98
- - This version is based on version 1.x.x of `ssh2`. This version of `ssh2` is a complete re-write of the `ssh2` library. This re-write addresses issues encountered when using node v14 as well as some design weaknesses in the previous 0.8.x version.
99
-
100
- - **Breaking Change** Expanded option handling for `get()` and `put()` methods. A number of use cases were identified where setting specific options on the read and write streams and the pipe operation are necessary. For example, disabling `autoClose` on streams or the `end` event in pipes. The `options` argument for `get()` and `put()` calls now supports properties for `readStreamOptions`, `writeStreamOptions` and `pipeOptions`. Note that options are only applied to streams created by the `get()` and `put()` methods. Streams passed into these methods are under the control of the client code and therefore cannot have options supplied in arguments to those streams (you would apply such options when you create the streams). Options are typically only necessary in special use cases. Most of the time, no options are required. However, if you are currently using options to either `put()` or `get()`, you will need to update your code to map these options to the new structure.
101
-
102
- - **Breaking Change 7.1.0** A race condition was identified when using a put() call with a writeStream option of `autoClose: false`. In some situations, the promise would be resolved before the final close of the write stream. This could result in errors if you immediately attempt to access the uploaded file. To avoid this situatioin, the promise is now resolved once a `close` event is emitted. This means that setting `autoClose: false` can no longer be supported. The write stream for `put()` will autoClose once data writing has completed.
103
-
104
- - Improved event handling. A listener for a global error event is now defined to catch errors which occur in-between method calls i.e. connection lost in-between calls to the library methods. A new mechanism has also been added for removal of listeners when no longer required.
105
-
106
- - uploadDir/downloadDir change in 7.2.3. THe uploadDir() and downloadDir() methods previously used fastPut() and fastGet() to transfer data. Unfortunately, not all SFTP servers support the concurrent processing used by these methods. This meant these methods would fail on some platforms. For now, the fastPut() and fastGet() calls have been replaced with plain put() and get() calls. This will mean uploadDir()/downloadDir() will be slower. However, there is other larger changes in the works which should see a significant speed imp[rovement for these (and other methods). We may also add an option which will allow for selection of fastPut()/fastGet().
107
-
108
- # Documentation<a id="sec-5"></a>
102
+ # Documentation<a id="sec-4"></a>
109
103
 
110
104
  The connection options are the same as those offered by the underlying SSH2 module. For full details, please see [SSH2 client methods](https://github.com/mscdex/ssh2#user-content-client-methods)
111
105
 
112
106
  All the methods will return a Promise, except for `on()` and `removeListener()`, which are typically only used in special use cases.
113
107
 
114
- ## Specifying Paths<a id="sec-5-1"></a>
108
+ ## Specifying Paths<a id="sec-4-1"></a>
115
109
 
116
110
  The convention with both FTP and SFTP is that paths are specified using a 'nix' style i.e. use `/` as the path separator. This means that even if your SFTP server is running on a win32 platform, you should use `/` instead of `\` as the path separator. For example, for a win32 path of `C:\Users\fred` you would actually use `/C:/Users/fred`. If your win32 server does not support the 'nix' path convention, you can try setting the `remotePathSep` property of the `SftpClient` object to the path separator of your remote server. This **might** work, but has not been tested. Please let me know if you need to do this and provide details of the SFTP server so that I can try to create an appropriate environment and adjust things as necessary. At this point, I'm not aware of any win32 based SFTP servers which do not support the 'nix' path convention.
117
111
 
@@ -141,9 +135,9 @@ client.put('/home/fred/test.txt', '/remote/dir/test-copy.txt');
141
135
 
142
136
  This will copy the local file `test.txt` to the remote file `test-copy.txt` in the directory `/remote/dir`.
143
137
 
144
- ## Methods<a id="sec-5-2"></a>
138
+ ## Methods<a id="sec-4-2"></a>
145
139
 
146
- ### new SftpClient(name) ===> SFTP client object<a id="sec-5-2-1"></a>
140
+ ### new SftpClient(name) ===> SFTP client object<a id="sec-4-2-1"></a>
147
141
 
148
142
  Constructor to create a new `ssh2-sftp-client` object. An optional `name` string can be provided, which will be used in error messages to help identify which client has thrown the error.
149
143
 
@@ -179,7 +173,7 @@ Constructor to create a new `ssh2-sftp-client` object. An optional `name` string
179
173
  });
180
174
  ```
181
175
 
182
- ### connect(config) ===> SFTP object<a id="sec-5-2-2"></a>
176
+ ### connect(config) ===> SFTP object<a id="sec-4-2-2"></a>
183
177
 
184
178
  Connect to an sftp server. Full documentation for connection options is available [here](https://github.com/mscdex/ssh2#user-content-client-methods)
185
179
 
@@ -242,7 +236,7 @@ Connect to an sftp server. Full documentation for connection options is availabl
242
236
  });
243
237
  ```
244
238
 
245
- ### list(path, pattern) ==> Array[object]<a id="sec-5-2-3"></a>
239
+ ### list(path, pattern) ==> Array[object]<a id="sec-4-2-3"></a>
246
240
 
247
241
  Retrieves a directory listing. This method returns a Promise, which once realised, returns an array of objects representing items in the remote directory.
248
242
 
@@ -309,7 +303,7 @@ Retrieves a directory listing. This method returns a Promise, which once realise
309
303
 
310
304
  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.
311
305
 
312
- ### exists(path) ==> boolean<a id="sec-5-2-4"></a>
306
+ ### exists(path) ==> boolean<a id="sec-4-2-4"></a>
313
307
 
314
308
  Tests to see if remote file or directory exists. Returns type of remote object if it exists or false if it does not.
315
309
 
@@ -342,7 +336,7 @@ Tests to see if remote file or directory exists. Returns type of remote object i
342
336
  });
343
337
  ```
344
338
 
345
- ### stat(path) ==> object<a id="sec-5-2-5"></a>
339
+ ### stat(path) ==> object<a id="sec-4-2-5"></a>
346
340
 
347
341
  Returns the attributes associated with the object pointed to by `path`.
348
342
 
@@ -390,7 +384,7 @@ Returns the attributes associated with the object pointed to by `path`.
390
384
  });
391
385
  ```
392
386
 
393
- ### get(path, dst, options) ==> String|Stream|Buffer<a id="sec-5-2-6"></a>
387
+ ### get(path, dst, options) ==> String|Stream|Buffer<a id="sec-4-2-6"></a>
394
388
 
395
389
  Retrieve a file from a remote SFTP server. The `dst` argument defines the destination and can be either a string, a stream object or undefined. If it is a string, it is interpreted as the path to a location on the local file system (path should include the file name). If it is a stream object, the remote data is passed to it via a call to pipe(). If `dst` is undefined, the method will put the data into a buffer and return that buffer when the Promise is resolved. If `dst` is defined, it is returned when the Promise is resolved.
396
390
 
@@ -443,7 +437,7 @@ In general, if you're going to pass in a string as the destination, you are bett
443
437
 
444
438
  - **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'.
445
439
 
446
- ### fastGet(remotePath, localPath, options) ===> string<a id="sec-5-2-7"></a>
440
+ ### fastGet(remotePath, localPath, options) ===> string<a id="sec-4-2-7"></a>
447
441
 
448
442
  Downloads a file at remotePath to localPath using parallel reads for faster throughput. This is the simplest method if you just want to download a file.
449
443
 
@@ -483,7 +477,7 @@ Downloads a file at remotePath to localPath using parallel reads for faster thro
483
477
  });
484
478
  ```
485
479
 
486
- ### put(src, remotePath, options) ==> string<a id="sec-5-2-8"></a>
480
+ ### put(src, remotePath, options) ==> string<a id="sec-4-2-8"></a>
487
481
 
488
482
  Upload data from local system to remote server. If the `src` argument is a string, it is interpreted as a local file path to be used for the data to transfer. If the `src` argument is a buffer, the contents of the buffer are copied to the remote file and if it is a readable stream, the contents of that stream are piped to the `remotePath` on the server.
489
483
 
@@ -530,7 +524,7 @@ Upload data from local system to remote server. If the `src` argument is a strin
530
524
 
531
525
  - **Tip:** If the src argument is a path string, consider just using `fastPut()`.
532
526
 
533
- ### fastPut(localPath, remotePath, options) ==> string<a id="sec-5-2-9"></a>
527
+ ### fastPut(localPath, remotePath, options) ==> string<a id="sec-4-2-9"></a>
534
528
 
535
529
  Uploads the data in file at `localPath` to a new file on remote server at `remotePath` using concurrency. The options object allows tweaking of the fast put process.
536
530
 
@@ -571,7 +565,7 @@ Uploads the data in file at `localPath` to a new file on remote server at `remot
571
565
  });
572
566
  ```
573
567
 
574
- ### append(input, remotePath, options) ==> string<a id="sec-5-2-10"></a>
568
+ ### append(input, remotePath, options) ==> string<a id="sec-4-2-10"></a>
575
569
 
576
570
  Append the `input` data to an existing remote file. There is no integrity checking performed apart from normal writeStream checks. This function simply opens a writeStream on the remote file in append mode and writes the data passed in to the file.
577
571
 
@@ -612,7 +606,7 @@ Append the `input` data to an existing remote file. There is no integrity checki
612
606
  });
613
607
  ```
614
608
 
615
- ### mkdir(path, recursive) ==> string<a id="sec-5-2-11"></a>
609
+ ### mkdir(path, recursive) ==> string<a id="sec-4-2-11"></a>
616
610
 
617
611
  Create a new directory. If the recursive flag is set to true, the method will create any directories in the path which do not already exist. Recursive flag defaults to false.
618
612
 
@@ -637,7 +631,7 @@ Create a new directory. If the recursive flag is set to true, the method will cr
637
631
  });
638
632
  ```
639
633
 
640
- ### rmdir(path, recursive) ==> string<a id="sec-5-2-12"></a>
634
+ ### rmdir(path, recursive) ==> string<a id="sec-4-2-12"></a>
641
635
 
642
636
  Remove a directory. If removing a directory and recursive flag is set to `true`, the specified directory and all sub-directories and files will be deleted. If set to false and the directory has sub-directories or files, the action will fail.
643
637
 
@@ -664,7 +658,7 @@ Remove a directory. If removing a directory and recursive flag is set to `true`,
664
658
  });
665
659
  ```
666
660
 
667
- ### delete(path, noErrorOK) ==> string<a id="sec-5-2-13"></a>
661
+ ### delete(path, noErrorOK) ==> string<a id="sec-4-2-13"></a>
668
662
 
669
663
  Delete a file on the remote server.
670
664
 
@@ -690,7 +684,7 @@ Delete a file on the remote server.
690
684
  });
691
685
  ```
692
686
 
693
- ### rename(fromPath, toPath) ==> string<a id="sec-5-2-14"></a>
687
+ ### rename(fromPath, toPath) ==> string<a id="sec-4-2-14"></a>
694
688
 
695
689
  Rename a file or directory from `fromPath` to `toPath`. You must have the necessary permissions to modify the remote file.
696
690
 
@@ -716,7 +710,7 @@ Rename a file or directory from `fromPath` to `toPath`. You must have the necess
716
710
  });
717
711
  ```
718
712
 
719
- ### posixRename(fromPath, toPath) ==> string<a id="sec-5-2-15"></a>
713
+ ### posixRename(fromPath, toPath) ==> string<a id="sec-4-2-15"></a>
720
714
 
721
715
  This method uses the openssh POSIX rename extension introduced in OpenSSH 4.8. The advantage of this version of rename over standard SFTP rename is that it is an atomic operation and will allow renaming a resource where the destination name exists. The POSIX rename will also work on some filesystems which do not support standard SFTP rename because they don't support the system hardlink() call. The POSIX rename extension is available on all openSSH servers from 4.8 and some other implementations. This is an extension to the standard SFTP protocol and therefore is not supported on all sSFTP servers.
722
716
 
@@ -740,7 +734,7 @@ client.connect(config)
740
734
  });
741
735
  ```
742
736
 
743
- ### chmod(path, mode) ==> string<a id="sec-5-2-16"></a>
737
+ ### chmod(path, mode) ==> string<a id="sec-4-2-16"></a>
744
738
 
745
739
  Change the mode (read, write or execute permissions) of a remote file or directory.
746
740
 
@@ -766,7 +760,7 @@ Change the mode (read, write or execute permissions) of a remote file or directo
766
760
  });
767
761
  ```
768
762
 
769
- ### realPath(path) ===> string<a id="sec-5-2-17"></a>
763
+ ### realPath(path) ===> string<a id="sec-4-2-17"></a>
770
764
 
771
765
  Converts a relative path to an absolute path on the remote server. This method is mainly used internally to resolve remote path names.
772
766
 
@@ -774,81 +768,83 @@ Converts a relative path to an absolute path on the remote server. This method i
774
768
 
775
769
  - **path:** A file path, either relative or absolute. Can handle '.' and '..', but does not expand '~'.
776
770
 
777
- ### cwd() ==> string<a id="sec-5-2-18"></a>
771
+ ### cwd() ==> string<a id="sec-4-2-18"></a>
778
772
 
779
773
  Returns what the server believes is the current remote working directory.
780
774
 
781
- ### uploadDir(srcDir, dstDir, filter) ==> string<a id="sec-5-2-19"></a>
775
+ ### uploadDir(srcDir, dstDir, filter) ==> string<a id="sec-4-2-19"></a>
782
776
 
783
777
  Upload the directory specified by `srcDir` to the remote directory specified by `dstDir`. The `dstDir` will be created if necessary. Any sub directories within `srcDir` will also be uploaded. Any existing files in the remote path will be overwritten.
784
778
 
785
- The upload process also emits 'upload' events. These events are fired for each successfully uploaded file. The `upload` event calls listeners with 1 argument, an object which has properties source and destination. The source property is the path of the file uploaded and the destination property is the path to where the file was uploaded to. The purpose of this event is to provide some way for client code to get feedback on the upload progress. You can add your own lisener using the `on()` method.
779
+ The upload process also emits 'upload' events. These events are fired for each successfully uploaded file. The `upload` event calls listeners with 1 argument, an object which has properties source and destination. The source property is the path of the file uploaded and the destination property is the path to where the file was uploaded. The purpose of this event is to provide some way for client code to get feedback on the upload progress. You can add your own listener using the `on()` method.
786
780
 
787
- The optionsl *filter* argument is a regular expression which can be used to select which files and directories to include in the upload.
781
+ The optionsl *filter* argument is a function which will be called for each item to be uploaded. The function will be called with two arguments. The first argument is the full path of the item to be uploaded and the second argument is a boolean, which will be true if the target path is for a directory. The filter function will be called for each item in the source path. If the function returns true, the item will be uploaded. If it returns false, it will be filtered and not uploaded. The filter function is called via the `Array.filter` method. These array comprehension methods are known to be unsafe for asynchronous functions. Therefore, only synchronous filter functions are supported at this time.
788
782
 
789
783
  - **srcDir:** A local file path specified as a string
790
784
  - **dstDir:** A remote file path specified as a string
791
- - **filter:** A regular expression used to filter which files and directories to include in the upload
785
+ - **filter:** A filter predicate function which is called for each item in the source path. The argument will receive two arguments. The first is the full path to the item and the second is a boolean which will be true if the item is a directory. If the function returns true, the item will be uploaded, otherwise it will be filtered out and ignored.
792
786
 
793
787
  1. Example
794
788
 
795
789
  ```javascript
796
- 'use strict';
790
+ 'use strict';
797
791
 
798
- // Example of using the uploadDir() method to upload a directory
799
- // to a remote SFTP server
792
+ // Example of using the uploadDir() method to upload a directory
793
+ // to a remote SFTP server
800
794
 
801
- const path = require('path');
802
- const SftpClient = require('../src/index');
795
+ const path = require('path');
796
+ const SftpClient = require('../src/index');
803
797
 
804
- const dotenvPath = path.join(__dirname, '..', '.env');
805
- require('dotenv').config({path: dotenvPath});
798
+ const dotenvPath = path.join(__dirname, '..', '.env');
799
+ require('dotenv').config({path: dotenvPath});
806
800
 
807
- const config = {
808
- host: process.env.SFTP_SERVER,
809
- username: process.env.SFTP_USER,
810
- password: process.env.SFTP_PASSWORD,
811
- port: process.env.SFTP_PORT || 22
812
- };
801
+ const config = {
802
+ host: process.env.SFTP_SERVER,
803
+ username: process.env.SFTP_USER,
804
+ password: process.env.SFTP_PASSWORD,
805
+ port: process.env.SFTP_PORT || 22
806
+ };
813
807
 
814
- async function main() {
815
- const client = new SftpClient('upload-test');
816
- const src = path.join(__dirname, '..', 'test', 'testData', 'upload-src');
817
- const dst = '/home/tim/upload-test';
808
+ async function main() {
809
+ const client = new SftpClient('upload-test');
810
+ const src = path.join(__dirname, '..', 'test', 'testData', 'upload-src');
811
+ const dst = '/home/tim/upload-test';
818
812
 
819
- try {
820
- await client.connect(config);
821
- client.on('upload', info => {
822
- console.log(`Listener: Uploaded ${info.source}`);
823
- });
824
- let rslt = await client.uploadDir(src, dst);
825
- return rslt;
826
- } finally {
827
- client.end();
813
+ try {
814
+ await client.connect(config);
815
+ client.on('upload', info => {
816
+ console.log(`Listener: Uploaded ${info.source}`);
817
+ });
818
+ let rslt = await client.uploadDir(src, dst);
819
+ return rslt;
820
+ } catch (err) {
821
+ console.error(err);
822
+ } finally {
823
+ client.end();
824
+ }
828
825
  }
829
- }
830
826
 
831
- main()
832
- .then(msg => {
833
- console.log(msg);
834
- })
835
- .catch(err => {
836
- console.log(`main error: ${err.message}`);
837
- });
827
+ main()
828
+ .then(msg => {
829
+ console.log(msg);
830
+ })
831
+ .catch(err => {
832
+ console.log(`main error: ${err.message}`);
833
+ });
838
834
 
839
835
  ```
840
836
 
841
- ### downloadDir(srcDir, dstDir, filter) ==> string<a id="sec-5-2-20"></a>
837
+ ### downloadDir(srcDir, dstDir, filter) ==> string<a id="sec-4-2-20"></a>
842
838
 
843
839
  Download the remote directory specified by `srcDir` to the local file system directory specified by `dstDir`. The `dstDir` directory will be created if required. All sub directories within `srcDir` will also be copied. Any existing files in the local path will be overwritten. No files in the local path will be deleted.
844
840
 
845
841
  The method also emites `download` events to provide a way to monitor download progress. The download event listener is called with one argument, an object with two properties, source and destination. The source property is the path to the remote file that has been downloaded and the destination is the local path to where the file was downloaded to. You can add a listener for this event using the `on()` method.
846
842
 
847
- The optional *filter* argument is a regular expression which can be used to select which files and directories will be downloaded from the remote server.
843
+ The optional *filter* argument is a predicate function which will be called with two arguments for each potential item to be downloaded. The first argument is the full path of the item and the second argument is a boolean, which will be true if the item is a directory. If the function returns true, the item will be included in the download. If it returns false, it will be filtered and ignored. The filter function is called via the `Array.filter` method. These array comprehension methods are known to be unsafe for asynchronous functions. Therefore, only synchronous filter functions are supported at this time.
848
844
 
849
845
  - **srcDir:** A remote file path specified as a string
850
846
  - **dstDir:** A local file path specified as a string
851
- - **filter:** A regular expression used to match the files and directories to be downloaded
847
+ - **filter:** A predicate function called with two arguments, the full path to an item and a boolean value which will be true if the item is a directory. The function is called for each item in the download path.
852
848
 
853
849
  1. Example
854
850
 
@@ -898,7 +894,7 @@ The optional *filter* argument is a regular expression which can be used to sele
898
894
 
899
895
  ```
900
896
 
901
- ### end() ==> boolean<a id="sec-5-2-21"></a>
897
+ ### end() ==> boolean<a id="sec-4-2-21"></a>
902
898
 
903
899
  Ends the current client session, releasing the client socket and associated resources. This function also removes all listeners associated with the client.
904
900
 
@@ -919,7 +915,7 @@ Ends the current client session, releasing the client socket and associated reso
919
915
  });
920
916
  ```
921
917
 
922
- ### Add and Remove Listeners<a id="sec-5-2-22"></a>
918
+ ### Add and Remove Listeners<a id="sec-4-2-22"></a>
923
919
 
924
920
  Although normally not required, you can add and remove custom listeners on the ssh2 client object. This object supports a number of events, but only a few of them have any meaning in the context of SFTP. These are
925
921
 
@@ -937,15 +933,15 @@ Although normally not required, you can add and remove custom listeners on the s
937
933
 
938
934
  Removes the specified listener from the event specified in eventType. Note that the `end()` method automatically removes all listeners from the client object.
939
935
 
940
- # Platform Quirks & Warnings<a id="sec-6"></a>
936
+ # Platform Quirks & Warnings<a id="sec-5"></a>
941
937
 
942
- ## Server Capabilities<a id="sec-6-1"></a>
938
+ ## Server Capabilities<a id="sec-5-1"></a>
943
939
 
944
940
  All SFTP servers and platforms are not equal. Some facilities provided by `ssh2-sftp-client` either depend on capabilities of the remote server or the underlying capabilities of the remote server platform. As an example, consider `chmod()`. This command depends on a remote filesystem which implements the 'nix' concept of users and groups. The *win32* platform does not have the same concept of users and groups, so `chmod()` will not behave in the same way.
945
941
 
946
942
  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.
947
943
 
948
- ## Promises, Events & Managing Exceptions<a id="sec-6-2"></a>
944
+ ## Promises, Events & Managing Exceptions<a id="sec-5-2"></a>
949
945
 
950
946
  One of the challenges in providing a Promise based API over a module like SSH2, which is event based is how to ensure events are handled appropriately. The challenge is due to the synchronous nature of events. You cannot use `try/catch` for events because you have no way of knowing when the event might fire. For example, it could easily fire after your `try/catch` block as completed execution.
951
947
 
@@ -961,25 +957,25 @@ The other area where additional events are fired is during the end() call. To de
961
957
 
962
958
  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.
963
959
 
964
- ### Adding Custom Handlers<a id="sec-6-2-1"></a>
960
+ ### Adding Custom Handlers<a id="sec-5-2-1"></a>
965
961
 
966
962
  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.
967
963
 
968
- ## Windows Based Servers<a id="sec-6-3"></a>
964
+ ## Windows Based Servers<a id="sec-5-3"></a>
969
965
 
970
966
  It appears that when the sftp server is running on Windows, a *ECONNRESET* error signal is raised when the end() method is called. Unfortunately, this signal is raised after a considerable delay. This means we cannot remove the error handler used in the end() promise as otherwise you will get an uncaught exception error. Leaving the handler in place, even though we will ignore this error, solves that issue, but unfortunately introduces a new problem. Because we are not removing the listener, if you re-use the client object for subsequent connections, an additional error handler will be added. If this happens more than 11 times, you will eventually see the Node warning about a possible memory leak. This is because node monitors the number of error handlers and if it sees more than 11 added to an object, it assumes there is a problem and generates the warning.
971
967
 
972
968
  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.
973
969
 
974
- ## Don't Re-use SftpClient Objects<a id="sec-6-4"></a>
970
+ ## Don't Re-use SftpClient Objects<a id="sec-5-4"></a>
975
971
 
976
972
  Due to an issue with *ECONNRESET* error signals when connecting to Windows based SFTP servers, it is not possible to remove the error handler in the end() method. This means that if you re-use the SftpClient object for multiple connections e.g. calling connect(), then end(), then connect() etc, you run the risk of multiple error handlers being added to the SftpClient object. After 11 handlers have been added, Node will generate a possible memory leak warning.
977
973
 
978
974
  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.
979
975
 
980
- # FAQ<a id="sec-7"></a>
976
+ # FAQ<a id="sec-6"></a>
981
977
 
982
- ## Remote server drops connections with only an end event<a id="sec-7-1"></a>
978
+ ## Remote server drops connections with only an end event<a id="sec-6-1"></a>
983
979
 
984
980
  Many SFTP servers have rate limiting protection which will drop connections once a limit has been reached. In particular, openSSH has the setting `MaxStartups`, which can be a tuple of the form `max:drop:full` where `max` is the maximum allowed unauthenticated connections, `drop` is a percentage value which specifies percentage of connections to be dropped once `max` connections has been reached and `full` is the number of connections at which point all subsequent connections will be dropped. e.g. `10:30:60` means allow up to 10 unauthenticated connections after which drop 30% of connection attempts until reaching 60 unauthenticated connections, at which time, drop all attempts.
985
981
 
@@ -987,7 +983,7 @@ Clients first make an unauthenticated connection to the SFTP server to begin neg
987
983
 
988
984
  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.
989
985
 
990
- ## How can I pass writable stream as dst for get method?<a id="sec-7-2"></a>
986
+ ## How can I pass writable stream as dst for get method?<a id="sec-6-2"></a>
991
987
 
992
988
  If the dst argument passed to the get method is a writeable stream, the remote file will be piped into that writeable. If the writeable you pass in is a writeable stream created with `fs.createWriteStream()`, the data will be written to the file specified in the constructor call to `createWriteStream()`.
993
989
 
@@ -1043,7 +1039,7 @@ sftp
1043
1039
  });
1044
1040
  ```
1045
1041
 
1046
- ## How can I upload files without having to specify a password?<a id="sec-7-3"></a>
1042
+ ## How can I upload files without having to specify a password?<a id="sec-6-3"></a>
1047
1043
 
1048
1044
  There are a couple of ways to do this. Essentially, you want to setup SSH keys and use these for authentication to the remote server.
1049
1045
 
@@ -1075,7 +1071,7 @@ sftp.connect({
1075
1071
  }
1076
1072
  ```
1077
1073
 
1078
- ## How can I connect through a Socks Proxy<a id="sec-7-4"></a>
1074
+ ## How can I connect through a Socks Proxy<a id="sec-6-4"></a>
1079
1075
 
1080
1076
  This solution was provided by @jmorino.
1081
1077
 
@@ -1108,13 +1104,13 @@ client.connect({
1108
1104
  // client is connected
1109
1105
  ```
1110
1106
 
1111
- ## Timeout while waiting for handshake or handshake errors<a id="sec-7-5"></a>
1107
+ ## Timeout while waiting for handshake or handshake errors<a id="sec-6-5"></a>
1112
1108
 
1113
1109
  Some users have encountered the error 'Timeout while waiting for handshake' or 'Handshake failed, no matching client->server ciphers. This is often due to the client not having the correct configuration for the transport layer algorithms used by ssh2. One of the connect options provided by the ssh2 module is `algorithm`, which is an object that allows you to explicitly set the key exchange, ciphers, hmac and compression algorithms as well as server host key used to establish the initial secure connection. See the SSH2 documentation for details. Getting these parameters correct usually resolves the issue.
1114
1110
 
1115
1111
  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.
1116
1112
 
1117
- ## How can I limit upload/download speed<a id="sec-7-6"></a>
1113
+ ## How can I limit upload/download speed<a id="sec-6-6"></a>
1118
1114
 
1119
1115
  If you want to limit the amount of bandwidth used during upload/download of data, you can use a stream to limit throughput. The following example was provided by *kennylbj*. Note that there is a caveat that we must set the `autoClose` flag to false to avoid calling an extra `_read()` on a closed stream that may cause \_get Permission Denied error in ssh2-streams.
1120
1116
 
@@ -1151,7 +1147,7 @@ try {
1151
1147
  }
1152
1148
  ```
1153
1149
 
1154
- ## Connection hangs or fails for larger files<a id="sec-7-7"></a>
1150
+ ## Connection hangs or fails for larger files<a id="sec-6-7"></a>
1155
1151
 
1156
1152
  This was contributed by Ladislav Jacho. Thanks.
1157
1153
 
@@ -1159,11 +1155,11 @@ A symptom of this issue is that you are able to upload small files, but uploadin
1159
1155
 
1160
1156
  For more explanation, see [issue #342](https://github.com/theophilusx/ssh2-sftp-client/issues/342).
1161
1157
 
1162
- # Examples<a id="sec-8"></a>
1158
+ # Examples<a id="sec-7"></a>
1163
1159
 
1164
1160
  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.
1165
1161
 
1166
- # Troubleshooting<a id="sec-9"></a>
1162
+ # Troubleshooting<a id="sec-8"></a>
1167
1163
 
1168
1164
  The `ssh2-sftp-client` module is essentially a wrapper around the `ssh2` and `ssh2-streams` modules, providing a higher level `promise` based API. When you run into issues, it is important to try and determine where the issue lies - either in the ssh2-sftp-client module or the underlying `ssh2` and `ssh2-streams` modules. One way to do this is to first identify a minimal reproducible example which reproduces the issue. Once you have that, try to replicate the functionality just using the `ssh2` and `ssh2-streams` modules. If the issue still occurs, then you can be fairly confident it is something related to those later 2 modules and therefore and issue which should be referred to the maintainer of that module.
1169
1165
 
@@ -1175,11 +1171,11 @@ Note also that in the repository there are two useful directories. The first is
1175
1171
 
1176
1172
  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.
1177
1173
 
1178
- ## Common Errors<a id="sec-9-1"></a>
1174
+ ## Common Errors<a id="sec-8-1"></a>
1179
1175
 
1180
1176
  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.
1181
1177
 
1182
- ### Not returning the promise in a `then()` block<a id="sec-9-1-1"></a>
1178
+ ### Not returning the promise in a `then()` block<a id="sec-8-1-1"></a>
1183
1179
 
1184
1180
  All methods in `ssh2-sftp-client` return a Promise. This means methods are executed *asynchrnously*. When you call a method inside the `then()` block of a promise chain, it is critical that you return the Promise that call generates. Failing to do this will result in the `then()` block completing and your code starting execution of the next `then()`, `catch()` or `finally()` block before your promise has been fulfilled. For example, the following will not do what you expect
1185
1181
 
@@ -1213,7 +1209,7 @@ Note the `return` statements. These ensure that the Promise returned by the clie
1213
1209
 
1214
1210
  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.
1215
1211
 
1216
- ### Mixing Promise Chains and Async/Await<a id="sec-9-1-2"></a>
1212
+ ### Mixing Promise Chains and Async/Await<a id="sec-8-1-2"></a>
1217
1213
 
1218
1214
  Another common error is to mix Promise chains and async/await calls. This is rarely a great idea. While you can do this, it tends to create complicated and difficult to maintain code. Select one approach and stick with it. Both approaches are functionally equivalent, so there is no reason to mix up the two paradigms. My personal preference would be to use async/await as I think that is more *natural* for most developers. For example, the following is more complex and difficult to follow than necessary (and has a bug!)
1219
1215
 
@@ -1270,7 +1266,7 @@ async function doSftp() {
1270
1266
  }
1271
1267
  ```
1272
1268
 
1273
- ### Try/catch and Error Handlers<a id="sec-9-1-3"></a>
1269
+ ### Try/catch and Error Handlers<a id="sec-8-1-3"></a>
1274
1270
 
1275
1271
  Another common error is to try and use a try/catch block to catch event signals, such as an error event. In general, you cannot use try/catch blocks for asynchronous code and expect errors to be caught by the `catch` block. Handling errors in asynchronous code is one of the key reasons we now have the Promise and async/await frameworks.
1276
1272
 
@@ -1278,17 +1274,17 @@ The basic problem is that the try/catch block will have completed execution befo
1278
1274
 
1279
1275
  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.
1280
1276
 
1281
- ### Server Differences<a id="sec-9-1-4"></a>
1277
+ ### Server Differences<a id="sec-8-1-4"></a>
1282
1278
 
1283
1279
  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.
1284
1280
 
1285
- ### Avoid Concurrent Operations<a id="sec-9-1-5"></a>
1281
+ ### Avoid Concurrent Operations<a id="sec-8-1-5"></a>
1286
1282
 
1287
1283
  Technically, SFTP should be able to perform multiple operations concurrently. As node is single threaded, what we a really talking about is running multiple execution contexts as a pool where node will switch contexts when each context is blocked due to things like waiting on network data etc. However, I have found this to be extremely unreliable and of very little benefit from a performance perspective. My recommendation is to therefore avoid executing multiple requests over the same connection in parallel (for example, generating multiple `get()` promises and using something like `Promise.all()` to resolve them.
1288
1284
 
1289
1285
  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.
1290
1286
 
1291
- ## Debugging Support<a id="sec-9-2"></a>
1287
+ ## Debugging Support<a id="sec-8-2"></a>
1292
1288
 
1293
1289
  You can add a `debug` property to the config object passed in to `connect()` to turn on debugging. This will generate quite a lot of output. The value of the property should be a function which accepts a single string argument. For example;
1294
1290
 
@@ -1318,7 +1314,7 @@ If you just want to see debug messages from `ssh2-sftp-client` and exclude debug
1318
1314
  }
1319
1315
  ```
1320
1316
 
1321
- # Logging Issues<a id="sec-10"></a>
1317
+ # Logging Issues<a id="sec-9"></a>
1322
1318
 
1323
1319
  Please log an issue for all bugs, questions, feature and enhancement requests. Please ensure you include the module version, node version and platform.
1324
1320
 
@@ -1332,7 +1328,7 @@ I am happy to try and help diagnose and fix any issues you encounter while using
1332
1328
 
1333
1329
  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.
1334
1330
 
1335
- # Pull Requests<a id="sec-11"></a>
1331
+ # Pull Requests<a id="sec-10"></a>
1336
1332
 
1337
1333
  Pull requests are always welcomed. However, please ensure your changes pass all tests and if you're adding a new feature, that tests for that feature are included. Likewise, for new features or enhancements, please include any relevant documentation updates.
1338
1334
 
@@ -1344,7 +1340,7 @@ This module will adopt a standard semantic versioning policy. Please indicate in
1344
1340
  - **Minor:** Minor change, enhancement or new feature which does not change existing API and will not break existing client code.
1345
1341
  - **Bug Fix:** No change to functionality or features. Simple fix of an existing bug.
1346
1342
 
1347
- # Contributors<a id="sec-12"></a>
1343
+ # Contributors<a id="sec-11"></a>
1348
1344
 
1349
1345
  This module was initially written by jyu213. On August 23rd, 2019, theophilusx took over responsibility for maintaining this module. A number of other people have contributed to this module, but until now, this was not tracked. My intention is to credit anyone who contributes going forward.
1350
1346