React Native
React Native
Check Whether the Last SFTP Read Failed
See more SFTP Examples
Demonstrates the Chilkat SFtp.LastReadFailed method, which returns whether the most recent read for a handle failed. The only argument is the handle. A normal end-of-file is not a failure.
Background: A chunked read loop needs to tell three outcomes apart: more data, a clean end-of-file, and an actual error such as a dropped connection or a revoked handle.
LastReadFailed isolates the error case — it is false on a normal EOF read (which succeeds with zero bytes) and true for an empty, malformed, or already-closed handle — so the loop can stop cleanly on EOF but bail out with an error message on a genuine failure.Chilkat React Native Downloads
import { BinData, SFtp } from '@chilkat/react-native'
async function chilkatExample() {
// Demonstrates the SFtp.LastReadFailed method, which returns whether the most recent read for a
// handle failed. The only argument is the handle. A normal end-of-file is NOT a failure.
const sftp = new SFtp();
// Connect, authenticate, and initialize the SFTP subsystem.
const port = 22;
try {
await sftp.connectAsync('sftp.example.com', port);
} catch {
console.log(sftp.lastErrorText);
return;
}
// Normally you would not hard-code the password in source. You should instead obtain it
// from an interactive prompt, environment variable, or a secrets vault.
const password = 'mySshPassword';
try {
await sftp.authenticatePwAsync('mySshLogin', password);
} catch {
console.log(sftp.lastErrorText);
return;
}
try {
await sftp.initializeSftpAsync();
} catch {
console.log(sftp.lastErrorText);
return;
}
let handle: string;
try {
handle = await sftp.openFileAsync('subdir/data.txt', 'readOnly', 'openExisting');
} catch {
console.log(sftp.lastErrorText);
return;
}
let reading = true;
const chunkSize = 4096;
const bd = new BinData();
while (reading) {
await sftp.readFileBdAsync(handle, chunkSize, bd);
// Distinguish an actual read failure from a normal EOF. On EOF the read succeeds, returns
// zero bytes, and LastReadFailed is false.
if (sftp.lastReadFailed(handle)) {
console.log(`Read failed: ${sftp.lastErrorText}`);
return;
}
reading = !sftp.eof(handle);
}
try {
await sftp.closeHandleAsync(handle);
} catch {
console.log(sftp.lastErrorText);
return;
}
console.log(`Read ${bd.numBytes} bytes with no read failures.`);
sftp.disconnect();
}