Skip to content

Sys.Sftp

Sys.Sftp transfers and manages files on SFTP servers from server-side code. withConnection() opens a connection, hands an ssh2-sftp-client client (npm package ssh2-sftp-client, version ^12.0.0) to your function, and closes the connection when the function is done.

Availability: Server

withConnection<T>(connectionOptions: Sftp.ConnectOptions, fn: (sftp: Sftp) => Promise<T>): Promise<T>

Connects to an SFTP server, runs the function with the connected client, and ends the connection afterwards, also when the function throws. The function’s result is returned.

ParameterTypeDescription
connectionOptionsSftp.ConnectOptionsConnection settings of ssh2-sftp-client, such as host, port, username, password or privateKey.
fn(sftp: Sftp) => Promise<T>Works with the connected client. See the ssh2-sftp-client documentation for its methods, such as list(), get(), put() and delete().

Returns: Promise<T>, the result of fn · Availability: Server

const fileNames = await Sys.Sftp.withConnection(
{ host: 'sftp.example.com', port: 22, username: 'export', password: secret },
async (sftp) => {
await sftp.put(reportBuffer, '/outbox/report.csv')
const files = await sftp.list('/inbox')
return files.map((file) => file.name)
},
)

Only use the client inside the function and wait for every call to finish there: the connection is closed as soon as the returned promise settles.