Sample code for 30+ languages & platforms
React Native

Write Text to a Remote SFTP File (Sequential)

See more SFTP Examples

Demonstrates the Chilkat SFtp.WriteFileText method, which encodes text using a charset and writes it at the current sequential write position of an open handle. The arguments are the handle, the charset, and the text.

Background: Chilkat tracks a write position per handle, so successive WriteFileText calls append naturally — the pattern for building a file a piece at a time, such as writing rows to a report. Opening with openOrCreate starts writing at the current end of the file. The charset determines the bytes actually stored, which matters whenever the text contains non-ASCII characters.

Chilkat React Native Downloads

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

async function chilkatExample() {
  // Demonstrates the SFtp.WriteFileText method, which encodes text and writes it at the current
  // sequential write position of an open handle.  The 1st argument is the handle, the 2nd is the
  // charset, and the 3rd is the text.

  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;
  }

  // Open (creating/truncating) the remote file for writing.
  let handle: string;
  try {
    handle = await sftp.openFileAsync('subdir/notes.txt', 'writeOnly', 'createTruncate');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // Write text as UTF-8.  Successive writes continue from where the previous write ended.
  try {
    await sftp.writeFileTextAsync(handle, 'utf-8', 'First line.\n');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  try {
    await sftp.writeFileTextAsync(handle, 'utf-8', 'Second line.\n');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

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

  console.log('Wrote text file.');

  sftp.disconnect();
}