React Native
React Native
Get the Byte Count of the Last SFTP Read
See more SFTP Examples
Demonstrates the Chilkat SFtp.LastReadNumBytes method, which returns the number of bytes received by the most recent read for a handle. The only argument is the handle.
Background: SFTP reads may return fewer bytes than requested even before the end of the file, so knowing the actual count is useful for tracking progress and for advancing an explicit offset by the right amount. Both a normal EOF read and a failed read report
0, so pair this with Eof and LastReadFailed to interpret a zero-byte result correctly.Chilkat React Native Downloads
import { BinData, SFtp } from '@chilkat/react-native'
async function chilkatExample() {
// Demonstrates the SFtp.LastReadNumBytes method, which returns the number of bytes received by
// the most recent read for a handle. The only argument is the handle.
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;
}
const bd = new BinData();
const chunkSize = 4096;
let reading = true;
while (reading) {
await sftp.readFileBdAsync(handle, chunkSize, bd);
if (sftp.lastReadFailed(handle)) {
console.log(sftp.lastErrorText);
return;
}
// Report how many bytes the last read actually returned. A normal EOF read reports 0.
const lastCount = sftp.lastReadNumBytes(handle);
console.log(`Last read returned ${lastCount} bytes.`);
reading = !sftp.eof(handle);
}
try {
await sftp.closeHandleAsync(handle);
} catch {
console.log(sftp.lastErrorText);
return;
}
console.log(`Total: ${bd.numBytes} bytes.`);
sftp.disconnect();
}