Sample code for 30+ languages & platforms
React Native

SFTP Read Text File

See more SFTP Examples

Demonstrates how to open a text file on the SSH server and read text.

Chilkat React Native Downloads

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

async function chilkatExample() {
  // This example assumes the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  const sftp = new SFtp();

  // Set some timeouts, in milliseconds:
  sftp.connectTimeoutMs = 5000;
  sftp.idleTimeoutMs = 15000;

  // Connect to the SSH server.  
  // The standard SSH port = 22
  // The hostname may be a hostname or IP address.
  const hostname = 'sftp.example.com';
  const port = 22;
  try {
    await sftp.connectAsync(hostname, port);
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // Authenticate with the SSH server.  Chilkat SFTP supports
  // both password-based authenication as well as public-key
  // authentication.  This example uses password authenication.
  try {
    await sftp.authenticatePwAsync('myLogin', 'myPassword');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // After authenticating, the SFTP subsystem must be initialized:
  try {
    await sftp.initializeSftpAsync();
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // Open a file for reading.
  let handle = '';
  try {
    handle = await sftp.openFileAsync('myTest.txt', 'readOnly', 'openExisting');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // Assume the file we are reading contains the following text:
  // abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ
  // (in ANSI format -- i.e. one byte per char).

  // Read 26 bytes:
  let sText = '';
  try {
    sText = await sftp.readFileTextAsync(handle, 26, 'ansi');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // Should print "abcdefghijklmnopqrstuvwxyz";
  console.log(sText);

  // Read the next 10 bytes.
  try {
    sText = await sftp.readFileTextAsync(handle, 10, 'ansi');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // Should print "1234567890";
  console.log(sText);

  // Read the next 26 bytes.
  try {
    sText = await sftp.readFileTextAsync(handle, 26, 'ansi');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // Should print "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  console.log(sText);

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

  console.log('Success.');
}