ssh2-sftp-client 9.0.4 → 10.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 +447 -370
- package/README.org +108 -106
- package/package.json +10 -10
- package/src/index.js +659 -587
- package/src/utils.js +78 -56
package/README.md
CHANGED
|
@@ -1,110 +1,103 @@
|
|
|
1
|
-
- [Overview](#
|
|
2
|
-
- [Version
|
|
3
|
-
- [Installation](#
|
|
4
|
-
- [Basic Usage](#
|
|
5
|
-
- [Documentation](#
|
|
6
|
-
- [Specifying Paths](#
|
|
7
|
-
- [Methods](#
|
|
8
|
-
- [new SftpClient(name) ===> SFTP client object](#
|
|
9
|
-
- [connect(config) ===> SFTP object](#
|
|
10
|
-
- [list(path, filter) ==> Array[object]](#
|
|
11
|
-
- [exists(path) ==> boolean](#
|
|
12
|
-
- [stat(path) ==> object](#
|
|
13
|
-
- [get(path, dst, options) ==> String|Stream|Buffer](#
|
|
14
|
-
- [fastGet(remotePath, localPath, options) ===> string](#
|
|
15
|
-
- [put(src, remotePath, options) ==> string](#
|
|
16
|
-
- [fastPut(localPath, remotePath, options) ==> string](#
|
|
17
|
-
- [append(input, remotePath, options) ==> string](#
|
|
18
|
-
- [mkdir(path, recursive) ==> string](#
|
|
19
|
-
- [rmdir(path, recursive) ==> string](#
|
|
20
|
-
- [delete(path, noErrorOK) ==> string](#
|
|
21
|
-
- [rename(fromPath, toPath) ==> string](#
|
|
22
|
-
- [posixRename(fromPath, toPath) ==> string](#
|
|
23
|
-
- [chmod(path, mode) ==> string](#
|
|
24
|
-
- [realPath(path) ===> string](#
|
|
25
|
-
- [cwd() ==> string](#
|
|
26
|
-
- [uploadDir(srcDir, dstDir, options) ==> string](#
|
|
27
|
-
- [downloadDir(srcDir, dstDir, options) ==> string](#
|
|
28
|
-
- [createReadStream(remotePath, options)) ==> stream object](#
|
|
29
|
-
- [createWriteStream(remotePath, options) ==> stream object](#
|
|
30
|
-
- [rcopy(srcPath, dstPath) ==> string](#
|
|
31
|
-
- [end() ==> boolean](#
|
|
32
|
-
- [Add and Remove Listeners](#
|
|
33
|
-
- [Platform Quirks & Warnings](#
|
|
34
|
-
- [Server Capabilities](#
|
|
35
|
-
- [Issues with `fastPut()` and `fastGet()` Methods](#
|
|
36
|
-
- [Promises, Events & Managing Exceptions](#
|
|
37
|
-
- [Adding Custom Handlers](#
|
|
38
|
-
- [Windows Based Servers](#
|
|
39
|
-
- [Don't Re-use SftpClient Objects](#
|
|
40
|
-
- [FAQ](#
|
|
41
|
-
- [Remote server drops connections with only an end event](#
|
|
42
|
-
- [How can I pass writeable stream as dst for get method?](#
|
|
43
|
-
- [How can I upload files without having to specify a password?](#
|
|
44
|
-
- [How can I connect through a Socks Proxy](#
|
|
45
|
-
- [Timeout while waiting for handshake or handshake errors](#
|
|
46
|
-
- [How can I limit upload/download speed](#
|
|
47
|
-
- [Connection hangs or fails for larger files](#
|
|
48
|
-
- [
|
|
49
|
-
- [
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
- [
|
|
53
|
-
- [
|
|
54
|
-
- [
|
|
55
|
-
- [
|
|
56
|
-
|
|
57
|
-
- [
|
|
58
|
-
- [
|
|
59
|
-
- [
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
1
|
+
- [Overview](#org4821cd9)
|
|
2
|
+
- [Version 10.0.0 Changes](#org196e8b6)
|
|
3
|
+
- [Installation](#orgeac23df)
|
|
4
|
+
- [Basic Usage](#orgda0ed58)
|
|
5
|
+
- [Documentation](#orgd0ca540)
|
|
6
|
+
- [Specifying Paths](#orgabfbdff)
|
|
7
|
+
- [Methods](#org35528cc)
|
|
8
|
+
- [new SftpClient(name) ===> SFTP client object](#org6d917af)
|
|
9
|
+
- [connect(config) ===> SFTP object](#org3ca98bb)
|
|
10
|
+
- [list(path, filter) ==> Array[object]](#org067b5c0)
|
|
11
|
+
- [exists(path) ==> boolean](#orgfde631c)
|
|
12
|
+
- [stat(path) ==> object](#orge6ccca9)
|
|
13
|
+
- [get(path, dst, options) ==> String|Stream|Buffer](#org63cf95f)
|
|
14
|
+
- [fastGet(remotePath, localPath, options) ===> string](#orga32496c)
|
|
15
|
+
- [put(src, remotePath, options) ==> string](#org6bdfd59)
|
|
16
|
+
- [fastPut(localPath, remotePath, options) ==> string](#org4296214)
|
|
17
|
+
- [append(input, remotePath, options) ==> string](#org01aa427)
|
|
18
|
+
- [mkdir(path, recursive) ==> string](#orge74ab72)
|
|
19
|
+
- [rmdir(path, recursive) ==> string](#org2692b91)
|
|
20
|
+
- [delete(path, noErrorOK) ==> string](#org59254a5)
|
|
21
|
+
- [rename(fromPath, toPath) ==> string](#org287873a)
|
|
22
|
+
- [posixRename(fromPath, toPath) ==> string](#orgb7290ba)
|
|
23
|
+
- [chmod(path, mode) ==> string](#org0e57abe)
|
|
24
|
+
- [realPath(path) ===> string](#org52444ca)
|
|
25
|
+
- [cwd() ==> string](#org34966e3)
|
|
26
|
+
- [uploadDir(srcDir, dstDir, options) ==> string](#org5c58fad)
|
|
27
|
+
- [downloadDir(srcDir, dstDir, options) ==> string](#orgb346779)
|
|
28
|
+
- [createReadStream(remotePath, options)) ==> stream object](#orga0edaaf)
|
|
29
|
+
- [createWriteStream(remotePath, options) ==> stream object](#org7287ad7)
|
|
30
|
+
- [rcopy(srcPath, dstPath) ==> string](#org4b84e95)
|
|
31
|
+
- [end() ==> boolean](#org6af9411)
|
|
32
|
+
- [Add and Remove Listeners](#org79d7176)
|
|
33
|
+
- [Platform Quirks & Warnings](#org8815934)
|
|
34
|
+
- [Server Capabilities](#orgcf08239)
|
|
35
|
+
- [Issues with `fastPut()` and `fastGet()` Methods](#org92f1dc4)
|
|
36
|
+
- [Promises, Events & Managing Exceptions](#org27f104a)
|
|
37
|
+
- [Adding Custom Handlers](#orgd903953)
|
|
38
|
+
- [Windows Based Servers](#orged5ee01)
|
|
39
|
+
- [Don't Re-use SftpClient Objects](#orgfafec91)
|
|
40
|
+
- [FAQ](#orgbe306ce)
|
|
41
|
+
- [Remote server drops connections with only an end event](#org9377d69)
|
|
42
|
+
- [How can I pass writeable stream as dst for get method?](#org0cf3ed0)
|
|
43
|
+
- [How can I upload files without having to specify a password?](#org14d1415)
|
|
44
|
+
- [How can I connect through a Socks Proxy](#org118bb9f)
|
|
45
|
+
- [Timeout while waiting for handshake or handshake errors](#orgc720a77)
|
|
46
|
+
- [How can I limit upload/download speed](#orge322728)
|
|
47
|
+
- [Connection hangs or fails for larger files](#org4164c6c)
|
|
48
|
+
- [Typescript definition file out of date](#orgd28c1e8)
|
|
49
|
+
- [Examples](#orgfab3156)
|
|
50
|
+
- [Troubleshooting](#orga11079b)
|
|
51
|
+
- [Common Errors](#org0372c41)
|
|
52
|
+
- [Not returning the promise in a `then()` block](#org0d8dc85)
|
|
53
|
+
- [Mixing Promise Chains and Async/Await](#org199b814)
|
|
54
|
+
- [Try/catch and Error Handlers](#org46e5412)
|
|
55
|
+
- [Server Differences](#org8a2ebba)
|
|
56
|
+
- [Avoid Concurrent Operations](#org24c4235)
|
|
57
|
+
- [Debugging Support](#org1d067af)
|
|
58
|
+
- [Logging Issues](#orgdc52f71)
|
|
59
|
+
- [Pull Requests](#orge4e0c24)
|
|
60
|
+
- [Contributors](#org7f7c9a1)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
<a id="org4821cd9"></a>
|
|
65
|
+
|
|
66
|
+
# Overview
|
|
63
67
|
|
|
64
68
|
an SFTP client for node.js, a wrapper around [SSH2](https://github.com/mscdex/ssh2) which provides a high level convenience abstraction as well as a Promise based API.
|
|
65
69
|
|
|
66
|
-
Documentation on the methods and available options in the underlying modules can be found on the [SSH2](https://github.com/mscdex/ssh2) project pages.
|
|
70
|
+
Documentation on the methods and available options in the underlying modules can be found on the [SSH2](https://github.com/mscdex/ssh2) project pages. As this module is really just a wrapper around the `ssh2` module, you will find lots of useful information, tips and examples in the `ssh2` repository.
|
|
67
71
|
|
|
68
|
-
Current stable release is
|
|
72
|
+
Current stable release is \*v10.0.0.
|
|
69
73
|
|
|
70
|
-
Code has been tested against Node versions
|
|
74
|
+
Code has been tested against Node versions 16.20.2, 18.18.2, 20.10.0 and 21.5.0. However, only versions from v18 are actively supported. It should also be noted that a significant performance improvement has been observed with versions >= 18. Version v16 is significantly slower.
|
|
71
75
|
|
|
72
|
-
Node versions <
|
|
76
|
+
Node versions < 16.x are not supported.
|
|
73
77
|
|
|
74
|
-
## Version 9.x Changes<a id="sec-1-1"></a>
|
|
75
78
|
|
|
76
|
-
|
|
77
|
-
- Fix bug in `end()` method where it was possible for the module to attempt calling the underlying ssh2 `end()` method when ssh2 has not been initialised. This could lead to undefined reference errors.
|
|
78
|
-
- Fix bug in `get()` method where supplied destination streams were not close, creating a possible resource leak. If the remote file did not exist, the method would return an error, but failed to close any passed in stream supplied as the destination for the data in the `get()` call.
|
|
79
|
-
- 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.
|
|
80
|
-
- Changed when event handled flags are reset. Now they are reset after a new set of temporary listeners are added.
|
|
81
|
-
- 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.
|
|
82
|
-
- Use nullish coalescing when setting retry parameters instead of or'ing with defaults. Allows setting values to 0.
|
|
83
|
-
- **Breaking Change**: This version uses syntax not supported in node versions prior to v14. Therefore, node versions less than v14 will not work.
|
|
84
|
-
- **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.
|
|
85
|
-
- **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!
|
|
86
|
-
- **Breaking Change**: The 3rd argument to `uploadDir()` and `downloadDir()` methods has been change. Previously, the argument was a filter function used to select which directories and files to be transferred. The 3rd argument is now an options object with two supported properties, `filter` and `useFastput` (for `uploadDir()`) or `useFastget` (for `downloadDir()`). If `useFastput` is true, the `fastPut()` method will be used to upload files. If `false` or missing, the slower, but better supported, `put()` method will be used. Likewise, the `useFastget` options can be set to `true` to use the `fastGet()` method for downloading files, otherwise the slower, but more reliable, `get()` method will be used.
|
|
87
|
-
- The `uploadDir()` and `downloadDir()` methods now use asynchronous processes to upload/download files. This should result in improved performance for these two methods.
|
|
88
|
-
- New Methods: Two new methods, `createWriteStream()` and `createReadStream()` have been added. These methods will return a stream object connected to a remote file on the `SFTP` server. Client code is responsible for managing these stream objects. This includes adding any necessary event listeners and disposing of the objects once finished with them.
|
|
89
|
-
- Re-factoring of Listeners: The library manages temporary listeners in order to provide a way to catch events and processes them inside a `Promise` context. Previously, every method added its own set of temporary listeners. However, this could result in multiple sets of listeners being added, especially for methods which call other methods as part of their processing e.g. `rmdir(),` `uploadDir()` and `dowqnloadDir()`. To avoid this, *internal only* versions of each method have been created. These internal methods use an *underscore* `_` prefix. Client code should not use these methods directly.
|
|
90
|
-
- New method: Added `rcopy()` method to perform a remote copy of a file on the remote SFTP server.
|
|
91
|
-
- Bumped ssh2 version to 1.11.0
|
|
79
|
+
<a id="org196e8b6"></a>
|
|
92
80
|
|
|
93
|
-
|
|
81
|
+
## Version 10.0.0 Changes
|
|
94
82
|
|
|
95
|
-
|
|
83
|
+
- The main change in this version is adding of limits on the number of promises which can be active at the same time. Version 9.1.0 extended the use of multiple promises to improve performance with downloadDir() and uploadDir(). However, for directories with really large numbers of files, this often resulted in an error because the methods would try to create more concurrent promises than was possible given available resources. This issue has been fixed by adding a new property called `promiseLimit`, which is limited to 10 by default. A new configuration property, `promiseLimit`, is now available for setting the maximum number of concurrent promises the downloadDir()/uploadDir() methods will create when downloading or uploading directory trees.
|
|
84
|
+
- Various minor documentation fixes and some minor fixes for typos in option property names.
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
<a id="orgeac23df"></a>
|
|
96
88
|
|
|
97
|
-
|
|
89
|
+
# Installation
|
|
98
90
|
|
|
91
|
+
```shell
|
|
99
92
|
npm install ssh2-sftp-client
|
|
100
93
|
```
|
|
101
94
|
|
|
102
|
-
# Basic Usage<a id="sec-3"></a>
|
|
103
95
|
|
|
104
|
-
|
|
96
|
+
<a id="orgda0ed58"></a>
|
|
105
97
|
|
|
106
|
-
|
|
98
|
+
# Basic Usage
|
|
107
99
|
|
|
100
|
+
```js
|
|
108
101
|
let Client = require('ssh2-sftp-client');
|
|
109
102
|
let sftp = new Client();
|
|
110
103
|
|
|
@@ -122,13 +115,21 @@ sftp.connect({
|
|
|
122
115
|
});
|
|
123
116
|
```
|
|
124
117
|
|
|
125
|
-
# Documentation<a id="sec-4"></a>
|
|
126
118
|
|
|
127
|
-
|
|
119
|
+
<a id="orgd0ca540"></a>
|
|
120
|
+
|
|
121
|
+
# Documentation
|
|
122
|
+
|
|
123
|
+
The connection options are the same as those offered by the underlying SSH2 module, with just a couple of additional properties added to tweak the `retry` parameters, add a `debug` function and set the `promiseLimit` property. For full details on the other properties, please see [SSH2 client methods](https://github.com/mscdex/ssh2#user-content-client-methods). In particular, see the `ssh2` documentation for details relating to setting various key exchange and encryption/signing algorithms used as part of the ssh2 protocol.
|
|
124
|
+
|
|
125
|
+
All the methods will return a Promise, except for `on(), ~removeListener()`, `createReadStream` and `createWriteStream`, which are typically only used in special use cases.
|
|
126
|
+
|
|
127
|
+
Note that I don't use Typescript and I don't maintain any typescript definition files. There are some typescript type definition files for this module, but they are maintained separately and have nothing to do with this project. Therefore, please do not log any issues arising from the use of these definition files with this project. Instead, refer your issues to the maintainers of those modules.
|
|
128
128
|
|
|
129
|
-
All the methods will return a Promise, except for `on()` and `removeListener()`, which are typically only used in special use cases.
|
|
130
129
|
|
|
131
|
-
|
|
130
|
+
<a id="orgabfbdff"></a>
|
|
131
|
+
|
|
132
|
+
## Specifying Paths
|
|
132
133
|
|
|
133
134
|
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.
|
|
134
135
|
|
|
@@ -141,35 +142,32 @@ There is a small performance hit for using `./` and `../` as the module must que
|
|
|
141
142
|
When specifying file paths, ensure to include a full path i.e. include the remote file name. Don't expect the module to append the local file name to the path you provide. For example, the following will not work
|
|
142
143
|
|
|
143
144
|
```javascript
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
145
|
client.put('/home/fred/test.txt', '/remote/dir');
|
|
148
146
|
```
|
|
149
147
|
|
|
150
148
|
will not result in the file `test.txt` being copied to `/remote/dir/test.txt`. You need to specify the target file name as well e.g.
|
|
151
149
|
|
|
152
150
|
```javascript
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
151
|
client.put('/home/fred/test.txt', '/remote/dir/test.txt');
|
|
157
152
|
```
|
|
158
153
|
|
|
159
154
|
Note that the remote file name does not have to be the same as the local file name. The following works fine;
|
|
160
155
|
|
|
161
156
|
```javascript
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
157
|
client.put('/home/fred/test.txt', '/remote/dir/test-copy.txt');
|
|
166
158
|
```
|
|
167
159
|
|
|
168
160
|
This will copy the local file `test.txt` to the remote file `test-copy.txt` in the directory `/remote/dir`.
|
|
169
161
|
|
|
170
|
-
## Methods<a id="sec-4-2"></a>
|
|
171
162
|
|
|
172
|
-
|
|
163
|
+
<a id="org35528cc"></a>
|
|
164
|
+
|
|
165
|
+
## Methods
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
<a id="org6d917af"></a>
|
|
169
|
+
|
|
170
|
+
### new SftpClient(name) ===> SFTP client object
|
|
173
171
|
|
|
174
172
|
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.
|
|
175
173
|
|
|
@@ -180,9 +178,6 @@ Constructor to create a new `ssh2-sftp-client` object. An optional `name` string
|
|
|
180
178
|
2. Example Use
|
|
181
179
|
|
|
182
180
|
```javascript
|
|
183
|
-
|
|
184
|
-
'use
|
|
185
|
-
|
|
186
181
|
'use strict';
|
|
187
182
|
|
|
188
183
|
const Client = require('ssh2-sftp-client');
|
|
@@ -208,7 +203,10 @@ Constructor to create a new `ssh2-sftp-client` object. An optional `name` string
|
|
|
208
203
|
});
|
|
209
204
|
```
|
|
210
205
|
|
|
211
|
-
|
|
206
|
+
|
|
207
|
+
<a id="org3ca98bb"></a>
|
|
208
|
+
|
|
209
|
+
### connect(config) ===> SFTP object
|
|
212
210
|
|
|
213
211
|
Connect to an sftp server. Full documentation for connection options is available [here](https://github.com/mscdex/ssh2#user-content-client-methods)
|
|
214
212
|
|
|
@@ -218,10 +216,9 @@ Connect to an sftp server. Full documentation for connection options is availabl
|
|
|
218
216
|
|
|
219
217
|
The `retries`, `retry_factor` and `retry_minTimeout` options are not part of the SSH2 module. These are part of the configuration for the [retry](https://www.npmjs.com/package/retry) package and what is used to enable retrying of sftp connection attempts. See the documentation for that package for an explanation of these values.
|
|
220
218
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
//
|
|
219
|
+
The `promiseLimit` is another option which is not part of the `ssh2` module and is specific to `ssh2-sftp-client`. It is a property used to limit the maximum number of concurrent promises possible when either downloading or uploading a directory tree using the `downloadDir()` or `uploadDir()` methods. The default setting for this property is 10. **NOTE**: bigger doe snot mean better. Many factors can affect what is the ideal setting for `promiseLimit`. If it is too large, any benefits are lost while node spends time switching contexts and/or withi the overheads associated with creating and cleaning up promises. Lots of factors can affect what the setting should be, including size of files, number of files, speed of network, version of node, capabilities of remote sftp server etc. A setting of 10 seems to be a reasonably good default and should be adequate for most use cases. However, if you feel it needs to be changed, I highly recommend that you benchmark different values to work out what is the best maximum size before you begin to see a performance drop off.
|
|
224
220
|
|
|
221
|
+
```javascript
|
|
225
222
|
// common options
|
|
226
223
|
|
|
227
224
|
let commonOpts {
|
|
@@ -235,12 +232,13 @@ Connect to an sftp server. Full documentation for connection options is availabl
|
|
|
235
232
|
privateKey: fs.readFileSync('/path/to/key'), // Buffer or string that contains
|
|
236
233
|
passphrase: 'a pass phrase', // string - For an encrypted private key
|
|
237
234
|
readyTimeout: 20000, // integer How long (in ms) to wait for the SSH handshake
|
|
238
|
-
strictVendor: true // boolean - Performs a strict server vendor check
|
|
239
|
-
debug: myDebug
|
|
235
|
+
strictVendor: true, // boolean - Performs a strict server vendor check
|
|
236
|
+
debug: myDebug,// function - Set this to a function that receives a single
|
|
240
237
|
// string argument to get detailed (local) debug information.
|
|
241
|
-
retries: 2 // integer. Number of times to retry connecting
|
|
242
|
-
retry_factor: 2 // integer. Time factor used to calculate time between retries
|
|
243
|
-
retry_minTimeout: 2000 // integer. Minimum timeout between attempts
|
|
238
|
+
retries: 2, // integer. Number of times to retry connecting
|
|
239
|
+
retry_factor: 2, // integer. Time factor used to calculate time between retries
|
|
240
|
+
retry_minTimeout: 2000, // integer. Minimum timeout between attempts
|
|
241
|
+
promiseLimit: 10, // max concurrent promises for downloadDir/uploadDir
|
|
244
242
|
};
|
|
245
243
|
|
|
246
244
|
// rarely used options
|
|
@@ -266,19 +264,18 @@ Connect to an sftp server. Full documentation for connection options is availabl
|
|
|
266
264
|
2. Example Use
|
|
267
265
|
|
|
268
266
|
```javascript
|
|
269
|
-
|
|
270
|
-
sftp.connect({
|
|
271
|
-
|
|
272
|
-
|
|
273
267
|
sftp.connect({
|
|
274
|
-
host: example.com,
|
|
268
|
+
host: 'example.com',
|
|
275
269
|
port: 22,
|
|
276
270
|
username: 'donald',
|
|
277
271
|
password: 'youarefired'
|
|
278
272
|
});
|
|
279
273
|
```
|
|
280
274
|
|
|
281
|
-
|
|
275
|
+
|
|
276
|
+
<a id="org067b5c0"></a>
|
|
277
|
+
|
|
278
|
+
### list(path, filter) ==> Array[object]
|
|
282
279
|
|
|
283
280
|
Retrieves a directory listing. This method returns a Promise, which once realised, returns an array of objects representing items in the remote directory.
|
|
284
281
|
|
|
@@ -288,9 +285,6 @@ Retrieves a directory listing. This method returns a Promise, which once realise
|
|
|
288
285
|
1. Example Use
|
|
289
286
|
|
|
290
287
|
```javascript
|
|
291
|
-
|
|
292
|
-
const
|
|
293
|
-
|
|
294
288
|
const Client = require('ssh2-sftp-client');
|
|
295
289
|
|
|
296
290
|
const config = {
|
|
@@ -300,7 +294,7 @@ Retrieves a directory listing. This method returns a Promise, which once realise
|
|
|
300
294
|
password: 'my-secret'
|
|
301
295
|
};
|
|
302
296
|
|
|
303
|
-
let sftp = new Client;
|
|
297
|
+
let sftp = new Client();
|
|
304
298
|
|
|
305
299
|
sftp.connect(config)
|
|
306
300
|
.then(() => {
|
|
@@ -321,24 +315,34 @@ Retrieves a directory listing. This method returns a Promise, which once realise
|
|
|
321
315
|
|
|
322
316
|
The objects in the array returned by `list()` have the following properties;
|
|
323
317
|
|
|
324
|
-
```
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
318
|
+
```javascript
|
|
319
|
+
{
|
|
320
|
+
type: '-', // file type(-, d, l)
|
|
321
|
+
name: 'example.txt', // file name
|
|
322
|
+
size: 43, // file size
|
|
323
|
+
modifyTime: 1675645360000, // file timestamp of modified time
|
|
324
|
+
accessTime: 1675645360000, // file timestamp of access time
|
|
325
|
+
rights: {
|
|
326
|
+
user: 'rw',
|
|
327
|
+
group: 'r',
|
|
328
|
+
other: 'r',
|
|
329
|
+
},
|
|
330
|
+
owner: 1000, // user ID
|
|
331
|
+
group: 1000, // group ID
|
|
332
|
+
longname: '-rw-r--r-- 1 fred fred 43 Feb 6 12:02 exaple.txt', // like ls -l line
|
|
333
|
+
}
|
|
330
334
|
```
|
|
331
335
|
|
|
332
|
-
|
|
336
|
+
|
|
337
|
+
<a id="orgfde631c"></a>
|
|
338
|
+
|
|
339
|
+
### exists(path) ==> boolean
|
|
333
340
|
|
|
334
341
|
Tests to see if remote file or directory exists. Returns type of remote object if it exists or false if it does not.
|
|
335
342
|
|
|
336
343
|
1. Example Use
|
|
337
344
|
|
|
338
345
|
```javascript
|
|
339
|
-
|
|
340
|
-
const
|
|
341
|
-
|
|
342
346
|
const Client = require('ssh2-sftp-client');
|
|
343
347
|
|
|
344
348
|
const config = {
|
|
@@ -348,7 +352,7 @@ Tests to see if remote file or directory exists. Returns type of remote object i
|
|
|
348
352
|
password: 'my-secret'
|
|
349
353
|
};
|
|
350
354
|
|
|
351
|
-
let sftp = new Client;
|
|
355
|
+
let sftp = new Client();
|
|
352
356
|
|
|
353
357
|
sftp.connect(config)
|
|
354
358
|
.then(() => {
|
|
@@ -365,7 +369,10 @@ Tests to see if remote file or directory exists. Returns type of remote object i
|
|
|
365
369
|
});
|
|
366
370
|
```
|
|
367
371
|
|
|
368
|
-
|
|
372
|
+
|
|
373
|
+
<a id="orge6ccca9"></a>
|
|
374
|
+
|
|
375
|
+
### stat(path) ==> object
|
|
369
376
|
|
|
370
377
|
Returns the attributes associated with the object pointed to by `path`.
|
|
371
378
|
|
|
@@ -376,9 +383,6 @@ Returns the attributes associated with the object pointed to by `path`.
|
|
|
376
383
|
The `stat()` method returns an object with the following properties;
|
|
377
384
|
|
|
378
385
|
```javascript
|
|
379
|
-
|
|
380
|
-
let
|
|
381
|
-
|
|
382
386
|
let stats = {
|
|
383
387
|
mode: 33279, // integer representing type and permissions
|
|
384
388
|
uid: 1000, // user ID
|
|
@@ -399,9 +403,6 @@ Returns the attributes associated with the object pointed to by `path`.
|
|
|
399
403
|
2. Example Use
|
|
400
404
|
|
|
401
405
|
```javascript
|
|
402
|
-
|
|
403
|
-
let
|
|
404
|
-
|
|
405
406
|
let client = new Client();
|
|
406
407
|
|
|
407
408
|
client.connect(config)
|
|
@@ -419,7 +420,10 @@ Returns the attributes associated with the object pointed to by `path`.
|
|
|
419
420
|
});
|
|
420
421
|
```
|
|
421
422
|
|
|
422
|
-
|
|
423
|
+
|
|
424
|
+
<a id="org63cf95f"></a>
|
|
425
|
+
|
|
426
|
+
### get(path, dst, options) ==> String|Stream|Buffer
|
|
423
427
|
|
|
424
428
|
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.
|
|
425
429
|
|
|
@@ -434,9 +438,6 @@ In general, if you're going to pass in a string as the destination, you are bett
|
|
|
434
438
|
The `options` argument can be used to pass options to the underlying streams and pipe call used by this method. The argument is an object with three possible properties, `readStreamOptions`, `writeStreamOptions` and `pipeOptions`. The values for each of these properties should be an object containing the required options. For example, possible read stream and pipe options could be defined as
|
|
435
439
|
|
|
436
440
|
```javascript
|
|
437
|
-
|
|
438
|
-
let
|
|
439
|
-
|
|
440
441
|
let options = {
|
|
441
442
|
readStreamOptions: {
|
|
442
443
|
flags: 'r',
|
|
@@ -456,9 +457,6 @@ In general, if you're going to pass in a string as the destination, you are bett
|
|
|
456
457
|
2. Example Use
|
|
457
458
|
|
|
458
459
|
```javascript
|
|
459
|
-
|
|
460
|
-
let
|
|
461
|
-
|
|
462
460
|
let client = new Client();
|
|
463
461
|
|
|
464
462
|
let remotePath = '/remote/server/path/file.txt';
|
|
@@ -478,9 +476,14 @@ In general, if you're going to pass in a string as the destination, you are bett
|
|
|
478
476
|
|
|
479
477
|
- **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'.
|
|
480
478
|
|
|
481
|
-
### fastGet(remotePath, localPath, options) ===> string<a id="sec-4-2-7"></a>
|
|
482
479
|
|
|
483
|
-
|
|
480
|
+
<a id="orga32496c"></a>
|
|
481
|
+
|
|
482
|
+
### fastGet(remotePath, localPath, options) ===> string
|
|
483
|
+
|
|
484
|
+
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. However, fastGet functionality depends heavily on remote sftp server capabilities and not all servers have the concurrency support required. See the Platform Quirks & Warnings section of this README.
|
|
485
|
+
|
|
486
|
+
Bottom line, when it works, it tends to work reliably. However, for many servers, it simply won't work or will result in truncated/corrupted data.
|
|
484
487
|
|
|
485
488
|
- **remotePath:** String. Path to the remote file to download
|
|
486
489
|
- **localPath:** String. Path on local file system for the downloaded file. The local path should include the filename to use for saving the file.
|
|
@@ -488,12 +491,13 @@ Downloads a file at remotePath to localPath using parallel reads for faster thro
|
|
|
488
491
|
|
|
489
492
|
1. Options
|
|
490
493
|
|
|
491
|
-
```
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
494
|
+
```javascript
|
|
495
|
+
{
|
|
496
|
+
concurrency: 64, // integer. Number of concurrent reads to use
|
|
497
|
+
chunkSize: 32768, // integer. Size of each read in bytes
|
|
498
|
+
step: function(total_transferred, chunk, total) // callback called each time a
|
|
499
|
+
// chunk is transferred
|
|
500
|
+
}
|
|
497
501
|
```
|
|
498
502
|
|
|
499
503
|
- **Warning:** Some servers do not respond correctly to requests to alter chunk size. This can result in lost or corrupted data.
|
|
@@ -501,9 +505,6 @@ Downloads a file at remotePath to localPath using parallel reads for faster thro
|
|
|
501
505
|
2. Sample Use
|
|
502
506
|
|
|
503
507
|
```javascript
|
|
504
|
-
|
|
505
|
-
let
|
|
506
|
-
|
|
507
508
|
let client = new Client();
|
|
508
509
|
let remotePath = '/server/path/file.txt';
|
|
509
510
|
let localPath = '/local/path/file.txt';
|
|
@@ -520,7 +521,10 @@ Downloads a file at remotePath to localPath using parallel reads for faster thro
|
|
|
520
521
|
});
|
|
521
522
|
```
|
|
522
523
|
|
|
523
|
-
|
|
524
|
+
|
|
525
|
+
<a id="org6bdfd59"></a>
|
|
526
|
+
|
|
527
|
+
### put(src, remotePath, options) ==> string
|
|
524
528
|
|
|
525
529
|
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.
|
|
526
530
|
|
|
@@ -532,12 +536,13 @@ Upload data from local system to remote server. If the `src` argument is a strin
|
|
|
532
536
|
|
|
533
537
|
The options object supports three properties, `readStreamOptions`, `writeStreamOptions` and `pipeOptions`. The value for each property should be an object with options as properties and their associated values representing the option value. For example, you might use the following to set `writeStream` options.
|
|
534
538
|
|
|
535
|
-
```
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
539
|
+
```javascript
|
|
540
|
+
{
|
|
541
|
+
writeStreamOptions: {
|
|
542
|
+
flags: 'w', // w - write and a - append
|
|
543
|
+
encoding: null, // use null for binary files
|
|
544
|
+
mode: 0o666, // mode to use for created file (rwx)
|
|
545
|
+
}}
|
|
541
546
|
```
|
|
542
547
|
|
|
543
548
|
The most common options to use are mode and encoding. The values shown above are the defaults. You do not have to set encoding to utf-8 for text files, null is fine for all file types. However, using utf-8 encoding for binary files will often result in data corruption.
|
|
@@ -547,9 +552,6 @@ Upload data from local system to remote server. If the `src` argument is a strin
|
|
|
547
552
|
2. Example Use
|
|
548
553
|
|
|
549
554
|
```javascript
|
|
550
|
-
|
|
551
|
-
let
|
|
552
|
-
|
|
553
555
|
let client = new Client();
|
|
554
556
|
|
|
555
557
|
let data = fs.createReadStream('/path/to/local/file.txt');
|
|
@@ -569,9 +571,14 @@ Upload data from local system to remote server. If the `src` argument is a strin
|
|
|
569
571
|
|
|
570
572
|
- **Tip:** If the src argument is a path string, consider just using `fastPut()`.
|
|
571
573
|
|
|
572
|
-
### fastPut(localPath, remotePath, options) ==> string<a id="sec-4-2-9"></a>
|
|
573
574
|
|
|
574
|
-
|
|
575
|
+
<a id="org4296214"></a>
|
|
576
|
+
|
|
577
|
+
### fastPut(localPath, remotePath, options) ==> string
|
|
578
|
+
|
|
579
|
+
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. Note that this functionality is heavily dependent on the capabilities of the remote sftp server, which must support the concurrency operations used by this method. This is not part of the standard and therefore is not available in all sftp servers. See the Platform Quirks & Warnings for more details.
|
|
580
|
+
|
|
581
|
+
Bottom line, when it works, it tends to work well. However, when it doesn't work, it may fail completely or it may result in truncated or corrupted data transfers.
|
|
575
582
|
|
|
576
583
|
- **localPath:** string. Path to local file to upload
|
|
577
584
|
- **remotePath:** string. Path to remote file to create
|
|
@@ -579,12 +586,14 @@ Uploads the data in file at `localPath` to a new file on remote server at `remot
|
|
|
579
586
|
|
|
580
587
|
1. Options
|
|
581
588
|
|
|
582
|
-
```
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
589
|
+
```javascript
|
|
590
|
+
{
|
|
591
|
+
concurrency: 64, // integer. Number of concurrent reads
|
|
592
|
+
chunkSize: 32768, // integer. Size of each read in bytes
|
|
593
|
+
mode: 0o755, // mixed. Integer or string representing the file mode to set
|
|
594
|
+
step: function(total_transferred, chunk, total) // function. Called every time
|
|
595
|
+
// a part of a file was transferred
|
|
596
|
+
}
|
|
588
597
|
```
|
|
589
598
|
|
|
590
599
|
- **Warning:** There have been reports that some SFTP servers will not honour requests for non-default chunk sizes. This can result in data loss or corruption.
|
|
@@ -592,9 +601,6 @@ Uploads the data in file at `localPath` to a new file on remote server at `remot
|
|
|
592
601
|
2. Example Use
|
|
593
602
|
|
|
594
603
|
```javascript
|
|
595
|
-
|
|
596
|
-
let
|
|
597
|
-
|
|
598
604
|
let localFile = '/path/to/file.txt';
|
|
599
605
|
let remoteFile = '/path/to/remote/file.txt';
|
|
600
606
|
let client = new Client();
|
|
@@ -611,7 +617,10 @@ Uploads the data in file at `localPath` to a new file on remote server at `remot
|
|
|
611
617
|
});
|
|
612
618
|
```
|
|
613
619
|
|
|
614
|
-
|
|
620
|
+
|
|
621
|
+
<a id="org01aa427"></a>
|
|
622
|
+
|
|
623
|
+
### append(input, remotePath, options) ==> string
|
|
615
624
|
|
|
616
625
|
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.
|
|
617
626
|
|
|
@@ -623,12 +632,13 @@ Append the `input` data to an existing remote file. There is no integrity checki
|
|
|
623
632
|
|
|
624
633
|
The following options are supported;
|
|
625
634
|
|
|
626
|
-
```
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
635
|
+
```javascript
|
|
636
|
+
{
|
|
637
|
+
flags: 'a', // w - write and a - append
|
|
638
|
+
encoding: null, // use null for binary files
|
|
639
|
+
mode: 0o666, // mode to use for created file (rwx)
|
|
640
|
+
autoClose: true // automatically close the write stream when finished
|
|
641
|
+
}
|
|
632
642
|
```
|
|
633
643
|
|
|
634
644
|
The most common options to use are mode and encoding. The values shown above are the defaults. You do not have to set encoding to utf-8 for text files, null is fine for all file types. Generally, I would not attempt to append binary files.
|
|
@@ -636,9 +646,6 @@ Append the `input` data to an existing remote file. There is no integrity checki
|
|
|
636
646
|
2. Example Use
|
|
637
647
|
|
|
638
648
|
```javascript
|
|
639
|
-
|
|
640
|
-
let
|
|
641
|
-
|
|
642
649
|
let remotePath = '/path/to/remote/file.txt';
|
|
643
650
|
let client = new Client();
|
|
644
651
|
|
|
@@ -654,7 +661,10 @@ Append the `input` data to an existing remote file. There is no integrity checki
|
|
|
654
661
|
});
|
|
655
662
|
```
|
|
656
663
|
|
|
657
|
-
|
|
664
|
+
|
|
665
|
+
<a id="orge74ab72"></a>
|
|
666
|
+
|
|
667
|
+
### mkdir(path, recursive) ==> string
|
|
658
668
|
|
|
659
669
|
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.
|
|
660
670
|
|
|
@@ -664,9 +674,6 @@ Create a new directory. If the recursive flag is set to true, the method will cr
|
|
|
664
674
|
1. Example Use
|
|
665
675
|
|
|
666
676
|
```javascript
|
|
667
|
-
|
|
668
|
-
let
|
|
669
|
-
|
|
670
677
|
let remoteDir = '/path/to/new/dir';
|
|
671
678
|
let client = new Client();
|
|
672
679
|
|
|
@@ -682,7 +689,10 @@ Create a new directory. If the recursive flag is set to true, the method will cr
|
|
|
682
689
|
});
|
|
683
690
|
```
|
|
684
691
|
|
|
685
|
-
|
|
692
|
+
|
|
693
|
+
<a id="org2692b91"></a>
|
|
694
|
+
|
|
695
|
+
### rmdir(path, recursive) ==> string
|
|
686
696
|
|
|
687
697
|
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.
|
|
688
698
|
|
|
@@ -694,9 +704,6 @@ Remove a directory. If removing a directory and recursive flag is set to `true`,
|
|
|
694
704
|
1. Example Use
|
|
695
705
|
|
|
696
706
|
```javascript
|
|
697
|
-
|
|
698
|
-
let
|
|
699
|
-
|
|
700
707
|
let remoteDir = '/path/to/remote/dir';
|
|
701
708
|
let client = new Client();
|
|
702
709
|
|
|
@@ -712,7 +719,10 @@ Remove a directory. If removing a directory and recursive flag is set to `true`,
|
|
|
712
719
|
});
|
|
713
720
|
```
|
|
714
721
|
|
|
715
|
-
|
|
722
|
+
|
|
723
|
+
<a id="org59254a5"></a>
|
|
724
|
+
|
|
725
|
+
### delete(path, noErrorOK) ==> string
|
|
716
726
|
|
|
717
727
|
Delete a file on the remote server.
|
|
718
728
|
|
|
@@ -723,9 +733,6 @@ Delete a file on the remote server.
|
|
|
723
733
|
1. Example Use
|
|
724
734
|
|
|
725
735
|
```javascript
|
|
726
|
-
|
|
727
|
-
let
|
|
728
|
-
|
|
729
736
|
let remoteFile = '/path/to/remote/file.txt';
|
|
730
737
|
let client = new Client();
|
|
731
738
|
|
|
@@ -741,7 +748,10 @@ Delete a file on the remote server.
|
|
|
741
748
|
});
|
|
742
749
|
```
|
|
743
750
|
|
|
744
|
-
|
|
751
|
+
|
|
752
|
+
<a id="org287873a"></a>
|
|
753
|
+
|
|
754
|
+
### rename(fromPath, toPath) ==> string
|
|
745
755
|
|
|
746
756
|
Rename a file or directory from `fromPath` to `toPath`. You must have the necessary permissions to modify the remote file.
|
|
747
757
|
|
|
@@ -751,9 +761,6 @@ Rename a file or directory from `fromPath` to `toPath`. You must have the necess
|
|
|
751
761
|
1. Example Use
|
|
752
762
|
|
|
753
763
|
```javascript
|
|
754
|
-
|
|
755
|
-
let
|
|
756
|
-
|
|
757
764
|
let from = '/remote/path/to/old.txt';
|
|
758
765
|
let to = '/remote/path/to/new.txt';
|
|
759
766
|
let client = new Client();
|
|
@@ -770,7 +777,10 @@ Rename a file or directory from `fromPath` to `toPath`. You must have the necess
|
|
|
770
777
|
});
|
|
771
778
|
```
|
|
772
779
|
|
|
773
|
-
|
|
780
|
+
|
|
781
|
+
<a id="orgb7290ba"></a>
|
|
782
|
+
|
|
783
|
+
### posixRename(fromPath, toPath) ==> string
|
|
774
784
|
|
|
775
785
|
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 file systems 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 sftp servers.
|
|
776
786
|
|
|
@@ -778,9 +788,6 @@ This method uses the openssh POSIX rename extension introduced in OpenSSH 4.8. T
|
|
|
778
788
|
- **toPath:** string. Path for new name. If it already exists, it will be replaced by file specified in fromPath
|
|
779
789
|
|
|
780
790
|
```javascript
|
|
781
|
-
|
|
782
|
-
let
|
|
783
|
-
|
|
784
791
|
let from = '/remote/path/to/old.txt';
|
|
785
792
|
let to = '/remote/path/to/new.txt';
|
|
786
793
|
let client = new Client();
|
|
@@ -797,7 +804,10 @@ client.connect(config)
|
|
|
797
804
|
});
|
|
798
805
|
```
|
|
799
806
|
|
|
800
|
-
|
|
807
|
+
|
|
808
|
+
<a id="org0e57abe"></a>
|
|
809
|
+
|
|
810
|
+
### chmod(path, mode) ==> string
|
|
801
811
|
|
|
802
812
|
Change the mode (read, write or execute permissions) of a remote file or directory.
|
|
803
813
|
|
|
@@ -807,9 +817,6 @@ Change the mode (read, write or execute permissions) of a remote file or directo
|
|
|
807
817
|
1. Example Use
|
|
808
818
|
|
|
809
819
|
```javascript
|
|
810
|
-
|
|
811
|
-
let
|
|
812
|
-
|
|
813
820
|
let path = '/path/to/remote/file.txt';
|
|
814
821
|
let newMode = 0o644; // rw-r-r
|
|
815
822
|
let client = new Client();
|
|
@@ -826,7 +833,10 @@ Change the mode (read, write or execute permissions) of a remote file or directo
|
|
|
826
833
|
});
|
|
827
834
|
```
|
|
828
835
|
|
|
829
|
-
|
|
836
|
+
|
|
837
|
+
<a id="org52444ca"></a>
|
|
838
|
+
|
|
839
|
+
### realPath(path) ===> string
|
|
830
840
|
|
|
831
841
|
Converts a relative path to an absolute path on the remote server. This method is mainly used internally to resolve remote path names.
|
|
832
842
|
|
|
@@ -834,11 +844,17 @@ Converts a relative path to an absolute path on the remote server. This method i
|
|
|
834
844
|
|
|
835
845
|
- **path:** A file path, either relative or absolute. Can handle '.' and '..', but does not expand '~'.
|
|
836
846
|
|
|
837
|
-
|
|
847
|
+
|
|
848
|
+
<a id="org34966e3"></a>
|
|
849
|
+
|
|
850
|
+
### cwd() ==> string
|
|
838
851
|
|
|
839
852
|
Returns what the server believes is the current remote working directory.
|
|
840
853
|
|
|
841
|
-
|
|
854
|
+
|
|
855
|
+
<a id="org5c58fad"></a>
|
|
856
|
+
|
|
857
|
+
### uploadDir(srcDir, dstDir, options) ==> string
|
|
842
858
|
|
|
843
859
|
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.
|
|
844
860
|
|
|
@@ -857,57 +873,57 @@ The `useFastput` option is a boolean option. If `true`, the method will use the
|
|
|
857
873
|
1. Example
|
|
858
874
|
|
|
859
875
|
```javascript
|
|
876
|
+
'use strict';
|
|
860
877
|
|
|
878
|
+
// Example of using the uploadDir() method to upload a directory
|
|
879
|
+
// to a remote SFTP server
|
|
861
880
|
|
|
881
|
+
const path = require('path');
|
|
882
|
+
const SftpClient = require('../src/index');
|
|
862
883
|
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
// Example of using the uploadDir() method to upload a directory
|
|
866
|
-
// to a remote SFTP server
|
|
867
|
-
|
|
868
|
-
const path = require('path');
|
|
869
|
-
const SftpClient = require('../src/index');
|
|
870
|
-
|
|
871
|
-
const dotenvPath = path.join(__dirname, '..', '.env');
|
|
872
|
-
require('dotenv').config({path: dotenvPath});
|
|
884
|
+
const dotenvPath = path.join(__dirname, '..', '.env');
|
|
885
|
+
require('dotenv').config({path: dotenvPath});
|
|
873
886
|
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
887
|
+
const config = {
|
|
888
|
+
host: process.env.SFTP_SERVER,
|
|
889
|
+
username: process.env.SFTP_USER,
|
|
890
|
+
password: process.env.SFTP_PASSWORD,
|
|
891
|
+
port: process.env.SFTP_PORT || 22
|
|
892
|
+
};
|
|
880
893
|
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
894
|
+
async function main() {
|
|
895
|
+
const client = new SftpClient('upload-test');
|
|
896
|
+
const src = path.join(__dirname, '..', 'test', 'testData', 'upload-src');
|
|
897
|
+
const dst = '/home/tim/upload-test';
|
|
885
898
|
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
+
try {
|
|
900
|
+
await client.connect(config);
|
|
901
|
+
client.on('upload', info => {
|
|
902
|
+
console.log(`Listener: Uploaded ${info.source}`);
|
|
903
|
+
});
|
|
904
|
+
let rslt = await client.uploadDir(src, dst);
|
|
905
|
+
return rslt;
|
|
906
|
+
} catch (err) {
|
|
907
|
+
console.error(err);
|
|
908
|
+
} finally {
|
|
909
|
+
client.end();
|
|
910
|
+
}
|
|
911
|
+
}
|
|
899
912
|
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
913
|
+
main()
|
|
914
|
+
.then(msg => {
|
|
915
|
+
console.log(msg);
|
|
916
|
+
})
|
|
917
|
+
.catch(err => {
|
|
918
|
+
console.log(`main error: ${err.message}`);
|
|
919
|
+
});
|
|
907
920
|
|
|
908
921
|
```
|
|
909
922
|
|
|
910
|
-
|
|
923
|
+
|
|
924
|
+
<a id="orgb346779"></a>
|
|
925
|
+
|
|
926
|
+
### downloadDir(srcDir, dstDir, options) ==> string
|
|
911
927
|
|
|
912
928
|
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.
|
|
913
929
|
|
|
@@ -924,9 +940,6 @@ If the `useFastget` property is set to `true`, the method will use `fastGet()` t
|
|
|
924
940
|
1. Example
|
|
925
941
|
|
|
926
942
|
```javascript
|
|
927
|
-
|
|
928
|
-
'use
|
|
929
|
-
|
|
930
943
|
'use strict';
|
|
931
944
|
|
|
932
945
|
// Example of using the downloadDir() method to upload a directory
|
|
@@ -972,7 +985,10 @@ If the `useFastget` property is set to `true`, the method will use `fastGet()` t
|
|
|
972
985
|
|
|
973
986
|
```
|
|
974
987
|
|
|
975
|
-
|
|
988
|
+
|
|
989
|
+
<a id="orga0edaaf"></a>
|
|
990
|
+
|
|
991
|
+
### createReadStream(remotePath, options)) ==> stream object
|
|
976
992
|
|
|
977
993
|
Returns a read stream object which is attached to the remote file specified by the `remotePath` argument. This is a low level method which just returns a read stream object. Client code is fully responsible for managing and releasing the resources associated with the stream once finished i.e. closing files, removing listeners etc.
|
|
978
994
|
|
|
@@ -986,7 +1002,10 @@ Returns a read stream object which is attached to the remote file specified by t
|
|
|
986
1002
|
- **start:** Default 0. Position to start reading bytes from (inclusive)
|
|
987
1003
|
- **end:** Position to stop reading bytes (inclusive).
|
|
988
1004
|
|
|
989
|
-
|
|
1005
|
+
|
|
1006
|
+
<a id="org7287ad7"></a>
|
|
1007
|
+
|
|
1008
|
+
### createWriteStream(remotePath, options) ==> stream object
|
|
990
1009
|
|
|
991
1010
|
Returns a write stream object which is attached to the remote file specified in the `remotePath` argument. This is a low level function which just returns the stream object. Client code is fully responsible for managing that object, including closing any file descriptors and removing listeners etc.
|
|
992
1011
|
|
|
@@ -998,23 +1017,26 @@ Returns a write stream object which is attached to the remote file specified in
|
|
|
998
1017
|
- **autoClose:** true
|
|
999
1018
|
- **start:** Byte position to start writing from (inclusive). May require changing flag to 'r+'.
|
|
1000
1019
|
|
|
1001
|
-
|
|
1020
|
+
|
|
1021
|
+
<a id="org4b84e95"></a>
|
|
1022
|
+
|
|
1023
|
+
### rcopy(srcPath, dstPath) ==> string
|
|
1002
1024
|
|
|
1003
1025
|
Perform a remote file copy. The file identified by the `srcPath` argument will be copied to the file specified as the `dstPath` argument. The directory where `dstPath` will be placed must exist, but the actual file must not i.e. no overwrites allowed.
|
|
1004
1026
|
|
|
1005
1027
|
- **srcPath:** Path to remote file to be copied specified as a string
|
|
1006
1028
|
- **dstPath:** Path to where the copy will be created specified as a string
|
|
1007
1029
|
|
|
1008
|
-
|
|
1030
|
+
|
|
1031
|
+
<a id="org6af9411"></a>
|
|
1032
|
+
|
|
1033
|
+
### end() ==> boolean
|
|
1009
1034
|
|
|
1010
1035
|
Ends the current client session, releasing the client socket and associated resources. This function also removes all listeners associated with the client.
|
|
1011
1036
|
|
|
1012
1037
|
1. Example Use
|
|
1013
1038
|
|
|
1014
1039
|
```javascript
|
|
1015
|
-
|
|
1016
|
-
let
|
|
1017
|
-
|
|
1018
1040
|
let client = new Client();
|
|
1019
1041
|
|
|
1020
1042
|
client.connect(config)
|
|
@@ -1029,7 +1051,10 @@ Ends the current client session, releasing the client socket and associated reso
|
|
|
1029
1051
|
});
|
|
1030
1052
|
```
|
|
1031
1053
|
|
|
1032
|
-
|
|
1054
|
+
|
|
1055
|
+
<a id="org79d7176"></a>
|
|
1056
|
+
|
|
1057
|
+
### Add and Remove Listeners
|
|
1033
1058
|
|
|
1034
1059
|
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
|
|
1035
1060
|
|
|
@@ -1047,21 +1072,33 @@ Although normally not required, you can add and remove custom listeners on the s
|
|
|
1047
1072
|
|
|
1048
1073
|
Removes the specified listener from the event specified in eventType. Note that the `end()` method automatically removes all listeners from the client object.
|
|
1049
1074
|
|
|
1050
|
-
# Platform Quirks & Warnings<a id="sec-5"></a>
|
|
1051
1075
|
|
|
1052
|
-
|
|
1076
|
+
<a id="org8815934"></a>
|
|
1077
|
+
|
|
1078
|
+
# Platform Quirks & Warnings
|
|
1079
|
+
|
|
1080
|
+
|
|
1081
|
+
<a id="orgcf08239"></a>
|
|
1082
|
+
|
|
1083
|
+
## Server Capabilities
|
|
1053
1084
|
|
|
1054
1085
|
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 file system 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.
|
|
1055
1086
|
|
|
1056
1087
|
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.
|
|
1057
1088
|
|
|
1058
|
-
|
|
1089
|
+
|
|
1090
|
+
<a id="org92f1dc4"></a>
|
|
1091
|
+
|
|
1092
|
+
## Issues with `fastPut()` and `fastGet()` Methods
|
|
1059
1093
|
|
|
1060
1094
|
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 specific packet size.
|
|
1061
1095
|
|
|
1062
1096
|
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.
|
|
1063
1097
|
|
|
1064
|
-
|
|
1098
|
+
|
|
1099
|
+
<a id="org27f104a"></a>
|
|
1100
|
+
|
|
1101
|
+
## Promises, Events & Managing Exceptions
|
|
1065
1102
|
|
|
1066
1103
|
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.
|
|
1067
1104
|
|
|
@@ -1077,25 +1114,40 @@ The other area where additional events are fired is during the end() call. To de
|
|
|
1077
1114
|
|
|
1078
1115
|
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.
|
|
1079
1116
|
|
|
1080
|
-
|
|
1117
|
+
|
|
1118
|
+
<a id="orgd903953"></a>
|
|
1119
|
+
|
|
1120
|
+
### Adding Custom Handlers
|
|
1081
1121
|
|
|
1082
1122
|
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.
|
|
1083
1123
|
|
|
1084
|
-
|
|
1124
|
+
|
|
1125
|
+
<a id="orged5ee01"></a>
|
|
1126
|
+
|
|
1127
|
+
## Windows Based Servers
|
|
1085
1128
|
|
|
1086
1129
|
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.
|
|
1087
1130
|
|
|
1088
1131
|
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.
|
|
1089
1132
|
|
|
1090
|
-
|
|
1133
|
+
|
|
1134
|
+
<a id="orgfafec91"></a>
|
|
1135
|
+
|
|
1136
|
+
## Don't Re-use SftpClient Objects
|
|
1091
1137
|
|
|
1092
1138
|
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.
|
|
1093
1139
|
|
|
1094
1140
|
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.
|
|
1095
1141
|
|
|
1096
|
-
# FAQ<a id="sec-6"></a>
|
|
1097
1142
|
|
|
1098
|
-
|
|
1143
|
+
<a id="orgbe306ce"></a>
|
|
1144
|
+
|
|
1145
|
+
# FAQ
|
|
1146
|
+
|
|
1147
|
+
|
|
1148
|
+
<a id="org9377d69"></a>
|
|
1149
|
+
|
|
1150
|
+
## Remote server drops connections with only an end event
|
|
1099
1151
|
|
|
1100
1152
|
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.
|
|
1101
1153
|
|
|
@@ -1103,16 +1155,16 @@ Clients first make an unauthenticated connection to the SFTP server to begin neg
|
|
|
1103
1155
|
|
|
1104
1156
|
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.
|
|
1105
1157
|
|
|
1106
|
-
|
|
1158
|
+
|
|
1159
|
+
<a id="org0cf3ed0"></a>
|
|
1160
|
+
|
|
1161
|
+
## How can I pass writeable stream as dst for get method?
|
|
1107
1162
|
|
|
1108
1163
|
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()`.
|
|
1109
1164
|
|
|
1110
1165
|
The writeable stream can be any type of write stream. For example, the below code will convert all the characters in the remote file to upper case before it is saved to the local file system. This could just as easily be something like a gunzip stream from `zlib`, enabling you to decompress remote zipped files as you bring them across before saving to local file system.
|
|
1111
1166
|
|
|
1112
1167
|
```javascript
|
|
1113
|
-
|
|
1114
|
-
'use
|
|
1115
|
-
|
|
1116
1168
|
'use strict';
|
|
1117
1169
|
|
|
1118
1170
|
// Example of using a writeable with get to retrieve a file.
|
|
@@ -1162,16 +1214,16 @@ sftp
|
|
|
1162
1214
|
});
|
|
1163
1215
|
```
|
|
1164
1216
|
|
|
1165
|
-
|
|
1217
|
+
|
|
1218
|
+
<a id="org14d1415"></a>
|
|
1219
|
+
|
|
1220
|
+
## How can I upload files without having to specify a password?
|
|
1166
1221
|
|
|
1167
1222
|
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.
|
|
1168
1223
|
|
|
1169
1224
|
One solution, provided by @KalleVuorjoki is to use the SSH agent process. **Note**: SSH<sub>AUTH</sub><sub>SOCK</sub> is normally created by your OS when you load the ssh-agent as part of the login session.
|
|
1170
1225
|
|
|
1171
1226
|
```javascript
|
|
1172
|
-
|
|
1173
|
-
let
|
|
1174
|
-
|
|
1175
1227
|
let sftp = new Client();
|
|
1176
1228
|
sftp.connect({
|
|
1177
1229
|
host: 'YOUR-HOST',
|
|
@@ -1186,9 +1238,6 @@ sftp.connect({
|
|
|
1186
1238
|
Another alternative is to just pass in the SSH key directly as part of the configuration.
|
|
1187
1239
|
|
|
1188
1240
|
```javascript
|
|
1189
|
-
|
|
1190
|
-
let
|
|
1191
|
-
|
|
1192
1241
|
let sftp = new Client();
|
|
1193
1242
|
sftp.connect({
|
|
1194
1243
|
host: 'YOUR-HOST',
|
|
@@ -1200,14 +1249,16 @@ sftp.connect({
|
|
|
1200
1249
|
}
|
|
1201
1250
|
```
|
|
1202
1251
|
|
|
1203
|
-
## How can I connect through a Socks Proxy<a id="sec-6-4"></a>
|
|
1204
1252
|
|
|
1205
|
-
|
|
1253
|
+
<a id="org118bb9f"></a>
|
|
1206
1254
|
|
|
1207
|
-
|
|
1255
|
+
## How can I connect through a Socks Proxy
|
|
1256
|
+
|
|
1257
|
+
This solution was provided by @jmorino.
|
|
1208
1258
|
|
|
1209
|
-
|
|
1259
|
+
When a SOCKS 5 client is connected it must be ingested by ssh2-sftp-client immediately, otherwise a timeout occurs.
|
|
1210
1260
|
|
|
1261
|
+
```javascript
|
|
1211
1262
|
import { SocksClient } from 'socks';
|
|
1212
1263
|
import SFTPClient from 'ssh2-sftp-client';
|
|
1213
1264
|
|
|
@@ -1215,7 +1266,7 @@ const host = 'my-sftp-server.net';
|
|
|
1215
1266
|
const port = 22; // default SSH/SFTP port on remote server
|
|
1216
1267
|
|
|
1217
1268
|
// connect to SOCKS 5 proxy
|
|
1218
|
-
const {
|
|
1269
|
+
const { socket } = await SocksClient.createConnection({
|
|
1219
1270
|
proxy: {
|
|
1220
1271
|
host: 'my.proxy', // proxy hostname
|
|
1221
1272
|
port: 1080, // proxy port
|
|
@@ -1228,79 +1279,91 @@ const { socks } = await SocksClient.createConnection({
|
|
|
1228
1279
|
const client = new SFTPClient();
|
|
1229
1280
|
client.connect({
|
|
1230
1281
|
host,
|
|
1231
|
-
sock:
|
|
1232
|
-
|
|
1233
|
-
privateKey: '.....'
|
|
1282
|
+
sock: socket, // pass the socket to proxy here (see ssh2 doc)
|
|
1283
|
+
// other config options
|
|
1234
1284
|
})
|
|
1235
1285
|
|
|
1236
1286
|
// client is connected
|
|
1237
1287
|
```
|
|
1238
1288
|
|
|
1239
|
-
|
|
1289
|
+
|
|
1290
|
+
<a id="orgc720a77"></a>
|
|
1291
|
+
|
|
1292
|
+
## Timeout while waiting for handshake or handshake errors
|
|
1240
1293
|
|
|
1241
1294
|
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.
|
|
1242
1295
|
|
|
1243
1296
|
When encountering this type of problem, one worthwhile approach is to use openSSH's CLI sftp program with the `-v` switch to raise logging 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.
|
|
1244
1297
|
|
|
1245
|
-
|
|
1298
|
+
|
|
1299
|
+
<a id="orge322728"></a>
|
|
1300
|
+
|
|
1301
|
+
## How can I limit upload/download speed
|
|
1246
1302
|
|
|
1247
1303
|
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.
|
|
1248
1304
|
|
|
1249
1305
|
```javascript
|
|
1250
1306
|
|
|
1251
1307
|
|
|
1308
|
+
const Throttle = require('throttle');
|
|
1309
|
+
const progress = require('progress-stream');
|
|
1252
1310
|
|
|
1311
|
+
// limit download speed
|
|
1312
|
+
const throttleStream = new Throttle(config.throttle);
|
|
1253
1313
|
|
|
1314
|
+
// download progress stream
|
|
1315
|
+
const progressStream = progress({
|
|
1316
|
+
length: fileSize,
|
|
1317
|
+
time: 500,
|
|
1318
|
+
});
|
|
1319
|
+
progressStream.on('progress', (progress) => {
|
|
1320
|
+
console.log(progress.percentage.toFixed(2));
|
|
1321
|
+
});
|
|
1254
1322
|
|
|
1323
|
+
const outStream = createWriteStream(localPath);
|
|
1255
1324
|
|
|
1325
|
+
// pipe streams together
|
|
1326
|
+
throttleStream.pipe(progressStream).pipe(outStream);
|
|
1256
1327
|
|
|
1328
|
+
try {
|
|
1329
|
+
// set autoClose to false
|
|
1330
|
+
await client.get(remotePath, throttleStream, { autoClose: false });
|
|
1331
|
+
} catch (e) {
|
|
1332
|
+
console.log('sftp error', e);
|
|
1333
|
+
} finally {
|
|
1334
|
+
await client.end();
|
|
1335
|
+
}
|
|
1336
|
+
```
|
|
1257
1337
|
|
|
1258
1338
|
|
|
1339
|
+
<a id="org4164c6c"></a>
|
|
1259
1340
|
|
|
1341
|
+
## Connection hangs or fails for larger files
|
|
1260
1342
|
|
|
1261
|
-
|
|
1262
|
-
const progress = require('progress-stream');
|
|
1343
|
+
This was contributed by Ladislav Jacho. Thanks.
|
|
1263
1344
|
|
|
1264
|
-
|
|
1265
|
-
const throttleStream = new Throttle(config.throttle);
|
|
1345
|
+
A symptom of this issue is that you are able to upload small files, but uploading larger ones fail. You probably have an MTU/fragmentation problem. For each network interface on both client and server set the MTU to 576, e.g. `ifconfig eth0 mtu 576`. If that works, you need to find the largest MTU which will work for your network. An MTU which is too small will adversely affect throughput speed. A common value to use is an MTU of 1400.
|
|
1266
1346
|
|
|
1267
|
-
|
|
1268
|
-
const progressStream = progress({
|
|
1269
|
-
length: fileSize,
|
|
1270
|
-
time: 500,
|
|
1271
|
-
});
|
|
1272
|
-
progressStream.on('progress', (progress) => {
|
|
1273
|
-
console.log(progress.percentage.toFixed(2));
|
|
1274
|
-
});
|
|
1347
|
+
For more explanation, see [issue #342](https://github.com/theophilusx/ssh2-sftp-client/issues/342).
|
|
1275
1348
|
|
|
1276
|
-
const outStream = createWriteStream(localPath);
|
|
1277
1349
|
|
|
1278
|
-
|
|
1279
|
-
throttleStream.pipe(progressStream).pipe(outStream);
|
|
1350
|
+
<a id="orgd28c1e8"></a>
|
|
1280
1351
|
|
|
1281
|
-
|
|
1282
|
-
// set autoClose to false
|
|
1283
|
-
await client.get(remotePath, throttleStream, { autoClose: false });
|
|
1284
|
-
} catch (e) {
|
|
1285
|
-
console.log('sftp error', e);
|
|
1286
|
-
} finally {
|
|
1287
|
-
await client.end();
|
|
1288
|
-
}
|
|
1289
|
-
```
|
|
1352
|
+
## Typescript definition file out of date
|
|
1290
1353
|
|
|
1291
|
-
|
|
1354
|
+
This project does not use Typescript. However, typescript definition files are provided by other 3rd parties. Sometimes, these definition files have not stayed up-to-date with the current version of this module. If you encounter this issue, you need to report it to the party responsible for the definition file, not this project.
|
|
1292
1355
|
|
|
1293
|
-
This was contributed by Ladislav Jacho. Thanks.
|
|
1294
1356
|
|
|
1295
|
-
|
|
1357
|
+
<a id="orgfab3156"></a>
|
|
1296
1358
|
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
# Examples<a id="sec-7"></a>
|
|
1359
|
+
# Examples
|
|
1300
1360
|
|
|
1301
1361
|
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.
|
|
1302
1362
|
|
|
1303
|
-
|
|
1363
|
+
|
|
1364
|
+
<a id="orga11079b"></a>
|
|
1365
|
+
|
|
1366
|
+
# Troubleshooting
|
|
1304
1367
|
|
|
1305
1368
|
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.
|
|
1306
1369
|
|
|
@@ -1312,18 +1375,21 @@ Note also that in the repository there are two useful directories. The first is
|
|
|
1312
1375
|
|
|
1313
1376
|
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.
|
|
1314
1377
|
|
|
1315
|
-
## Common Errors<a id="sec-8-1"></a>
|
|
1316
1378
|
|
|
1317
|
-
|
|
1379
|
+
<a id="org0372c41"></a>
|
|
1318
1380
|
|
|
1319
|
-
|
|
1381
|
+
## Common Errors
|
|
1320
1382
|
|
|
1321
|
-
|
|
1383
|
+
There are some common errors people tend to make when using Promises or Async/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.
|
|
1322
1384
|
|
|
1323
|
-
```javascript
|
|
1324
1385
|
|
|
1386
|
+
<a id="org0d8dc85"></a>
|
|
1325
1387
|
|
|
1388
|
+
### Not returning the promise in a `then()` block
|
|
1326
1389
|
|
|
1390
|
+
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
|
|
1391
|
+
|
|
1392
|
+
```javascript
|
|
1327
1393
|
sftp.connect(config)
|
|
1328
1394
|
.then(() => {
|
|
1329
1395
|
sftp.fastGet('foo.txt', 'bar.txt');
|
|
@@ -1338,9 +1404,6 @@ sftp.connect(config)
|
|
|
1338
1404
|
In the above code, the `sftp.end()` method will almost certainly be called before `sftp.fastGet()` has been fulfilled (unless the *foo.txt* file is really small!). In fact, the whole promise chain will complete and exit even before the `sftp.end()` call has been fulfilled. The correct code would be something like
|
|
1339
1405
|
|
|
1340
1406
|
```javascript
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
1407
|
sftp.connect(config)
|
|
1345
1408
|
.then(() => {
|
|
1346
1409
|
return sftp.fastGet('foo.txt', 'bar.txt');
|
|
@@ -1356,14 +1419,14 @@ Note the `return` statements. These ensure that the Promise returned by the clie
|
|
|
1356
1419
|
|
|
1357
1420
|
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.
|
|
1358
1421
|
|
|
1359
|
-
### Mixing Promise Chains and Async/Await<a id="sec-8-1-2"></a>
|
|
1360
|
-
|
|
1361
|
-
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!)
|
|
1362
1422
|
|
|
1363
|
-
|
|
1423
|
+
<a id="org199b814"></a>
|
|
1364
1424
|
|
|
1425
|
+
### Mixing Promise Chains and Async/Await
|
|
1365
1426
|
|
|
1427
|
+
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!)
|
|
1366
1428
|
|
|
1429
|
+
```javascript
|
|
1367
1430
|
sftp.connect(config)
|
|
1368
1431
|
.then(() => {
|
|
1369
1432
|
return sftp.cwd();
|
|
@@ -1386,9 +1449,6 @@ The main bug in the above code is the `then()` block is not returning the Promis
|
|
|
1386
1449
|
Using async/await inside the promise chain has created unnecessary complexity and leads to incorrect assumptions regarding how the code will execute. A quick glance at the code is likely to give the impression that execution will wait for the `sftp.fastGet()` call to be fulfilled before continuing. This is not the case. The code would be more clearly expressed as either
|
|
1387
1450
|
|
|
1388
1451
|
```javascript
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
1452
|
sftp.connect(config)
|
|
1393
1453
|
.then(() => {
|
|
1394
1454
|
return sftp.cwd();
|
|
@@ -1405,9 +1465,6 @@ sftp.connect(config)
|
|
|
1405
1465
|
**or, using async/await**
|
|
1406
1466
|
|
|
1407
1467
|
```javascript
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
1468
|
async function doSftp() {
|
|
1412
1469
|
try {
|
|
1413
1470
|
let sftp = await sftp.connect(conf);
|
|
@@ -1416,13 +1473,16 @@ async function doSftp() {
|
|
|
1416
1473
|
await sftp.fastGet(`${d}/foo.txt`, 'bat.txt');
|
|
1417
1474
|
} catch (e) {
|
|
1418
1475
|
console.error(e.message);
|
|
1419
|
-
} finally
|
|
1476
|
+
} finally {
|
|
1420
1477
|
await sftp.end();
|
|
1421
1478
|
}
|
|
1422
1479
|
}
|
|
1423
1480
|
```
|
|
1424
1481
|
|
|
1425
|
-
|
|
1482
|
+
|
|
1483
|
+
<a id="org46e5412"></a>
|
|
1484
|
+
|
|
1485
|
+
### Try/catch and Error Handlers
|
|
1426
1486
|
|
|
1427
1487
|
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.
|
|
1428
1488
|
|
|
@@ -1430,24 +1490,30 @@ The basic problem is that the try/catch block will have completed execution befo
|
|
|
1430
1490
|
|
|
1431
1491
|
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.
|
|
1432
1492
|
|
|
1433
|
-
|
|
1493
|
+
|
|
1494
|
+
<a id="org8a2ebba"></a>
|
|
1495
|
+
|
|
1496
|
+
### Server Differences
|
|
1434
1497
|
|
|
1435
1498
|
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.
|
|
1436
1499
|
|
|
1437
|
-
|
|
1500
|
+
|
|
1501
|
+
<a id="org24c4235"></a>
|
|
1502
|
+
|
|
1503
|
+
### Avoid Concurrent Operations
|
|
1438
1504
|
|
|
1439
1505
|
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.
|
|
1440
1506
|
|
|
1441
1507
|
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.
|
|
1442
1508
|
|
|
1443
|
-
## Debugging Support<a id="sec-8-2"></a>
|
|
1444
1509
|
|
|
1445
|
-
|
|
1510
|
+
<a id="org1d067af"></a>
|
|
1446
1511
|
|
|
1447
|
-
|
|
1512
|
+
## Debugging Support
|
|
1448
1513
|
|
|
1449
|
-
config.
|
|
1514
|
+
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;
|
|
1450
1515
|
|
|
1516
|
+
```javascript
|
|
1451
1517
|
config.debug = msg => {
|
|
1452
1518
|
console.error(msg);
|
|
1453
1519
|
};
|
|
@@ -1457,23 +1523,26 @@ config.debug = msg => {
|
|
|
1457
1523
|
Enabling debugging can generate a lot of output. If you use console.error() as the output (as in the example above), you can redirect the output to a file using shell redirection e.g.
|
|
1458
1524
|
|
|
1459
1525
|
```shell
|
|
1460
|
-
|
|
1461
|
-
node
|
|
1462
|
-
|
|
1463
1526
|
node script.js 2> debug.log
|
|
1464
1527
|
|
|
1465
1528
|
```
|
|
1466
1529
|
|
|
1467
1530
|
If you just want to see debug messages from `ssh2-sftp-client` and exclude debug messages from the underlying `ssh2` and `ssh2-streams` modules, you can filter based on messages which start with 'CLIENT' e.g.
|
|
1468
1531
|
|
|
1469
|
-
```
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1532
|
+
```javascript
|
|
1533
|
+
{
|
|
1534
|
+
debug: (msg) => {
|
|
1535
|
+
if (msg.startsWith('CLIENT')) {
|
|
1536
|
+
console.error(msg);
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1474
1540
|
```
|
|
1475
1541
|
|
|
1476
|
-
|
|
1542
|
+
|
|
1543
|
+
<a id="orgdc52f71"></a>
|
|
1544
|
+
|
|
1545
|
+
# Logging Issues
|
|
1477
1546
|
|
|
1478
1547
|
Please log an issue for all bugs, questions, feature and enhancement requests. Please ensure you include the module version, node version and platform.
|
|
1479
1548
|
|
|
@@ -1487,7 +1556,10 @@ I am happy to try and help diagnose and fix any issues you encounter while using
|
|
|
1487
1556
|
|
|
1488
1557
|
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.
|
|
1489
1558
|
|
|
1490
|
-
|
|
1559
|
+
|
|
1560
|
+
<a id="orge4e0c24"></a>
|
|
1561
|
+
|
|
1562
|
+
# Pull Requests
|
|
1491
1563
|
|
|
1492
1564
|
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.
|
|
1493
1565
|
|
|
@@ -1496,10 +1568,15 @@ Pull requests are always welcomed. However, please ensure your changes pass all
|
|
|
1496
1568
|
This module will adopt a standard semantic versioning policy. Please indicate in your pull request what level of change it represents i.e.
|
|
1497
1569
|
|
|
1498
1570
|
- **Major:** Change to API or major change in functionality which will require an increase in major version number.
|
|
1571
|
+
|
|
1499
1572
|
- **Minor:** Minor change, enhancement or new feature which does not change existing API and will not break existing client code.
|
|
1573
|
+
|
|
1500
1574
|
- **Bug Fix:** No change to functionality or features. Simple fix of an existing bug.
|
|
1501
1575
|
|
|
1502
|
-
|
|
1576
|
+
|
|
1577
|
+
<a id="org7f7c9a1"></a>
|
|
1578
|
+
|
|
1579
|
+
# Contributors
|
|
1503
1580
|
|
|
1504
1581
|
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.
|
|
1505
1582
|
|