Sample code for 30+ languages & platforms
React Native

Detect End-of-File on a Remote SFTP File

See more SFTP Examples

Demonstrates the Chilkat SFtp.Eof method, which returns whether the most recent read for a handle received the SFTP end-of-file status. The only argument is the handle. This example reads until Eof is true.

Background: The timing here is worth understanding: reading exactly through the final byte does not immediately set EOF. The next read succeeds, returns zero bytes, sets the status to SSH_FX_EOF, and only then does Eof report true. That is why the loop tests Eof after each read rather than assuming a short read means the end — a short read can also just be the server returning less than requested.

Chilkat React Native Downloads

React Native
import { SFtp, StringBuilder } from '@chilkat/react-native'

async function chilkatExample() {
  // Demonstrates the SFtp.Eof method, which returns whether the most recent read for a handle
  // received the SFTP end-of-file status.  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;
  }

  // Read until Eof reports the end of the file.  Note that reading exactly through the final byte
  // does not set EOF; the next read returns zero bytes and then Eof becomes true.
  const sbContent = new StringBuilder();
  const chunkSize = 4096;
  let reading = true;
  while (reading) {
    const chunk = await sftp.readFileTextAsync(handle, chunkSize, 'utf-8');
    if (sftp.lastReadFailed(handle)) {
      console.log(sftp.lastErrorText);
      return;
    }

    sbContent.append(chunk);
    reading = !sftp.eof(handle);
  }

  try {
    await sftp.closeHandleAsync(handle);
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  console.log(sbContent.getAsString());

  sftp.disconnect();
}