Sample code for 30+ languages & platforms
React Native

SFTP Fsync -- Flush an Open File on the Server

See more SFTP Examples

Demonstrates how to flush the contents of an open file on the server. This example only works for servers that implement the fsync@openssh.com extension.

Note: This example requires Chilkat v9.5.0.71 or later.

Chilkat React Native Downloads

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

async function chilkatExample() {
  let success = false;

  // This example assumes the Chilkat API to have been previously unlocked.
  // See Global Unlock Sample for sample code.

  const sftp = new SFtp();

  // Pass a domain or IP address..
  success = true;
  try {
    await sftp.connectAsync('my-sftp-server.com', 22);
  } catch {
    success = false;
  }
  if (success) {
    success = true;
    try {
      await sftp.authenticatePwAsync('mySFtpLogin', 'mySFtpPassword');
    } catch {
      success = false;
    }
  }

  if (success) {
    success = true;
    try {
      await sftp.initializeSftpAsync();
    } catch {
      success = false;
    }
  }

  if (!success) {
    console.log(sftp.lastErrorText);
    return;
  }

  // Open a file on the server for writing.
  let handle: string;
  try {
    handle = await sftp.openFileAsync('myTest.txt', 'writeOnly', 'createTruncate');
  } catch {
    console.log(sftp.lastErrorText);
    return;
  }

  // Write some text to the file:
  success = true;
  try {
    await sftp.writeFileTextAsync(handle, 'ansi', 'abcdefghijklmnopqrstuvwxyz');
  } catch {
    success = false;
  }
  if (!success) {
    console.log(sftp.lastErrorText);
    return;
  }

  // Make sure the server flushes what we wrote to the disk..
  // (this is requires a server that implements the fsync@openssh.com SFTP protocol extension)
  success = true;
  try {
    await sftp.fsyncAsync(handle);
  } catch {
    success = false;
  }
  if (!success) {
    console.log(sftp.lastErrorText);
    return;
  }

  // ....
  // ....

  success = true;
  try {
    await sftp.writeFileTextAsync(handle, 'ansi', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  } catch {
    success = false;
  }
  if (!success) {
    console.log(sftp.lastErrorText);
    return;
  }

  // Close the file.
  success = true;
  try {
    await sftp.closeHandleAsync(handle);
  } catch {
    success = false;
  }
  if (!success) {
    console.log(sftp.lastErrorText);
    return;
  }

  console.log('Success.');
}