React Native Requires Chilkat v11.0.0+
React Native
SFTP Read Directory Listing
See more SFTP Examples
Demonstrates how to download a directory listing and iterate over the files.Chilkat React Native Downloads
import { SFtp, SFtpDir, SFtpFile } from '@chilkat/react-native'
async function chilkatExample() {
// This requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
// Important: It is helpful to send the contents of the
// sftp.LastErrorText property when requesting support.
const sftp = new SFtp();
// Set some timeouts, in milliseconds:
sftp.connectTimeoutMs = 5000;
sftp.idleTimeoutMs = 10000;
// Connect to the SSH server.
// The standard SSH port = 22
// The hostname may be a hostname or IP address.
const hostname = 'www.my-sftp-server.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 directory on the server...
// Paths starting with a slash are "absolute", and are relative
// to the root of the file system. Names starting with any other
// character are relative to the user's default directory (home directory).
// A path component of ".." refers to the parent directory,
// and "." refers to the current directory.
let handle: string;
try {
handle = await sftp.openDirAsync('.');
} catch {
console.log(sftp.lastErrorText);
return;
}
// Download the directory listing:
const dirListing = new SFtpDir();
try {
await sftp.readDirListingAsync(handle, dirListing);
} catch {
console.log(sftp.lastErrorText);
return;
}
// Close the handle for the directory listing.
try {
await sftp.closeHandleAsync(handle);
} catch {
console.log(sftp.lastErrorText);
return;
}
// Iterate over the files.
const fileObj = new SFtpFile();
let i = 0;
const n = dirListing.numFilesAndDirs;
while (i < n) {
try {
dirListing.fileAt(i, fileObj);
} catch {
console.log(dirListing.lastErrorText);
return;
}
console.log(fileObj.filename);
console.log(fileObj.fileType);
console.log(`Size in bytes: ${fileObj.size32}`);
console.log('----');
i++;
}
console.log('Success.');
}