Sample code for 30+ languages & platforms
Lua

Flush an SFTP File to Stable Storage (Fsync)

See more SFTP Examples

Demonstrates the Chilkat SFtp.Fsync method, which requests that the server flush pending data for an open file to stable storage. The only argument is the handle. It uses the OpenSSH fsync@openssh.com extension and succeeds only when the server supports it.

Background: A successful write does not guarantee the data has reached disk — it may still sit in the server's write cache, where a crash or power loss would lose it. Fsync forces it to durable storage, which matters for transactional or journal-style files where a committed record must survive a failure. Because it relies on a non-standard OpenSSH extension, expect it to fail against servers that do not implement it, and treat that as a capability check rather than a hard error where appropriate.

Chilkat Lua Downloads

Lua
local chilkat = require("chilkat")

-- Demonstrates the SFtp.Fsync method, which requests that the server flush pending data for an
-- open file to stable storage.  The only argument is the handle.

local sftp = chilkat.SFtp.new()

-- Connect, authenticate, and initialize the SFTP subsystem.
local port = 22
local success = sftp:connect("sftp.example.com", port)
if not success then
    print(sftp.last_error_text)
    return
end

-- 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.
local password = "mySshPassword"

success = sftp:authenticate_pw("mySshLogin", password)
if not success then
    print(sftp.last_error_text)
    return
end

success = sftp:initialize_sftp()
if not success then
    print(sftp.last_error_text)
    return
end

local handle = sftp:open_file("subdir/journal.log", "writeOnly", "openOrCreate,appendData")
if not sftp.last_method_success then
    print(sftp.last_error_text)
    return
end

-- Write a critical record.
success = sftp:write_file_text(handle, "utf-8", "2026-07-23 transaction committed\n")
if not success then
    print(sftp.last_error_text)
    return
end

-- Ask the server to flush the data to durable storage before continuing.  Fsync uses the
-- OpenSSH fsync@openssh.com extension and succeeds only when the server supports it.
success = sftp:fsync(handle)
if not success then
    print(sftp.last_error_text)
    return
end

success = sftp:close_handle(handle)
if not success then
    print(sftp.last_error_text)
    return
end

print("Data flushed to stable storage.")

sftp:disconnect()