Module file

High level file handling library.

A file handle can be created through one of the constructor functions. File operations are performed on that handle.

Example to write and read-back a file:

local lgi = require("lgi")
local File = require("lgi-async-extra.file")
local path = "%s/foo.txt":format(lgi.GLib.get_tmp_dir())
local f = File.new_for_path(path)
async.waterfall({
    function(cb)
        -- By default, writing replaces any existing content
        f:write("hello", cb)
    end,
    function(cb)
        -- But we can also append to the file
        f:write("world", "append", cb)
    end,
    function(cb)
        f:read_string(cb)
    end,
}, function(err, data)
    print(err)
    print(data)
end)

License GPL v3.0

Table of contents

Constructors

new_for_path(path) Create a file handle for the given local path.
new_for_uri(uri) Create a file handle for the given remote URI.
new_tmp([template=".XXXXXX"]) Create a new file in a directory preferred for temporary storage.

Static functions

is_instance(f) Checks if a table is an instance of file.

Class file

File:get_path() Get the file’s path name.
File:read_stream(cb) Open a read stream.
File:write_stream([mode="replace"], cb) Open a write stream.
File:write(data[, mode="replace"], cb) Write the data to the opened file.
File:read_bytes(size, cb) Read at most the specified number of bytes from the file.
File:read_string(cb) Read the entire file’s content into memory.
File:read_line(cb) Read a line from the file.
File:iterate_lines(iteratee, cb) Asynchronously iterate over the file line by line.
File:move(path, cb) Move the file to a new location.
File:copy(dest_path, options, recursive, overwrite, cb) Copies the file to a new location.
File:delete(cb) Delete the file.
File:trash(cb) Move the file to trash.
File:query_info(attribute, cb) Query file information.
File:exists(cb) Check if the file exists.
File:size(cb) Query the size of the file.
File:type(cb) Query the type of the file.
File:create(cb) Creates an empty file.

Constructors

new_for_path(path) [src]
Create a file handle for the given local path.

This is a cheap operation, that only creates an in memory representation of the resource location. No I/O will take place until a corresponding method is called on the returned File object.

Parameters:

Returns:

  • type File
new_for_uri(uri) [src]
Create a file handle for the given remote URI.

This is a cheap operation, that only creates an in memory representation of the resource location. No I/O will take place until a corresponding method is called on the returned File object.

Parameters:

Returns:

  • type File
new_tmp([template=".XXXXXX"]) [src]
Create a new file in a directory preferred for temporary storage.

If template is given, it must contain a sequence of six Xs somewhere in the string, which will replaced by a unique ID to ensure the new file does not overwrite existing ones. The template must not contain any directory components. If template == nil, a default value will be used.

The directory is determined by g_get_tmp_dir.

The second return value is a Gio.FileIOStream, which contains both an input and output stream to the created file. The caller is responsible for closing these streams.

The third return value will be an instance of GLib.Error if the attempt to create the file failed. If this is not nil, attempts to access the other return values will result in undefined behavior.

See docs.gtk.org for additional details.

Parameters:

  • template
    type string
    default ".XXXXXX"

Returns:

  • type File
  • type GIO.FileIOStream
  • type GLib.Error

Static functions

is_instance(f) [src]
since v0.2.0
Checks if a table is an instance of file.

Parameters:

  • f :  The value to check.
    type table

Returns:

  • type boolean

Usage:

local File = require("lgi-async-extra.file")
local f = File.new_for_path("/tmp/foo.txt")
assert(File.is_instance(f))

Class file

File:get_path() [src]
since v0.2.0
Get the file’s path name.

The path is guaranteed to be absolute, by may contain unresolved symlinks. However, a path may not exist, in which case nil will be returned.

Returns:

File:read_stream(cb) [src]
async

Open a read stream.

The consumer is responsible for properly closing the stream:

stream:close_async(GLib.PRIORITY_DEFAULT, nil, function(_, token)
    local _, err = stream:close_finish(token)
    cb(err)
end)

A GDataInputStream adds additional reading utilities:

stream = Gio.DataInputStream.new(stream)

Parameters:

  • cb
    type function

Callback parameters:

  • type GLib.Error
  • type Gio.FileInputStream
File:write_stream([mode="replace"], cb) [src]
async

Open a write stream.

Write operations are buffered, so the stream needs to be flushed (or closed) to be sure that changes are written to disk. Especially in replace mode, reading before flushing will yield stale content.

The consumer is responsible for properly closing the stream:

stream:close_async(GLib.PRIORITY_DEFAULT, nil, function(_, token)
    local _, err = stream:close_finish(token)
    cb(err)
end)

Parameters:

  • mode :  Either "append" or "replace". "replace" will truncate the file before writing, "append" will keep any existing content and add the new data at the end.
    type string
    default "replace"
  • cb
    type function

Callback parameters:

  • type GLib.Error
  • type Gio.FileOutputStream
File:write(data[, mode="replace"], cb) [src]
async
Write the data to the opened file.

Parameters:

  • data :  The data to write.
    type string
  • mode :  Either "append" or "replace". "replace" will truncate the file before writing, "append" will keep any existing content and add the new data at the end.
    type string
    default "replace"
  • cb
    type function

Callback parameters:

  • type GLib.Error
File:read_bytes(size, cb) [src]
async
since v0.2.0
Read at most the specified number of bytes from the file.

If there is not enough data to read, the result may contain less than size bytes of data.

Parameters:

  • size :  The number of bytes to read.
    type number
  • cb :  The callback to call when reading finished. Signature: function(err, data)
    type function

Callback parameters:

  • An instance of GError if there was an error, nil otherwise.
    type GLib.Error
  • type GLib.Bytes
File:read_string(cb) [src]
async
since v0.2.0
Read the entire file’s content into memory.

This collects the content into a Lua string, so text files an be used as-is. For binary content, use string.byte to access the raw values or manually wrap the result of file:read_stream in a Gio.DataInputStream and read individual values based on their binary size.

Parameters:

  • cb :  The callback to call when reading finished. Signature: function(err, data)
    type function

Callback parameters:

  • An instance of GError if there was an error, nil otherwise.
    type GLib.Error
  • A string read from the file.
    type string
File:read_line(cb) [src]
async
Read a line from the file.

Like all other operations, this always reads from the beginning of the file. Calling this function repeatedly on the same file will always yield the first line.

To iterate over all lines, use file:iterate_lines. To read more than just one line, use file:read_bytes or file:read_string.

Parameters:

  • cb
    type function

Callback parameters:

  • An instance of GError if there was an error, nil otherwise.
    type GLib.Error
  • A string read from the file, or nil if the end was reached.
    type string
File:iterate_lines(iteratee, cb) [src]
async
since v0.2.0
Asynchronously iterate over the file line by line.

This function opens a read stream and starts reading the file line-wise, asynchronously. For every line read, the given iteratee is called with any potential error, the line’s content (without the trailing newline) and a callback function. The callback must always be called to ensure the file handle is cleaned up eventually. The expected signature for the callback is cb(err, stop). If err ~= nil or a value for stop is given, iteration stops immediately and cb will be called.

Changed 0.2.0: Renamed from read_lines.

Parameters:

  • iteratee :  Function to call per line in the file. Signature: function(err, line, cb)
    type function
  • cb :  Function to call when iteration has stopped. Signature: function(err).
    type function
File:move(path, cb) [src]
async
since v0.3.0
Move the file to a new location.

Due to limitations in GObject Introspection, this can currently only be implemented as “copy and delete” operation.

Parameters:

  • path :  New path to move to.
    type string or file
  • cb
    type function

Callback parameters:

  • type GLib.Error
File:copy(dest_path, options, recursive, overwrite, cb) [src]
async
since v0.3.0
Copies the file to a new location.

Parameters:

  • dest_path :  Path to copy to.
    type string or file
  • options
    type table
  • recursive :  Copy directory contents recursively.
    type boolean
  • overwrite :  Overwrite files at the destination path.
    type boolean
  • cb
    type function

Callback parameters:

  • type GLib.Error
File:delete(cb) [src]
async
Delete the file.

This has the same semantics as POSIX unlink(), i.e. the link at the given path is removed. If it was the last link to the file, the disk space occupied by that file is freed as well.

Empty directories are deleted by this as well.

Parameters:

  • cb
    type function

Callback parameters:

  • type GLib.Error
File:trash(cb) [src]
async
Move the file to trash.

Support for this depends on the platform and file system. If unsupported an error of type Gio.IOErrorEnum.NOT_SUPPORTED will be returned.

Parameters:

  • cb
    type function

Callback parameters:

  • type GLib.Error
File:query_info(attribute, cb) [src]
async
Query file information.

This can be used to query for any file info attribute supported by GIO. The attribute parameter may either be plain string, such as "standard::size", a wildcard "standard::*" or a list of both "standard::*,owner::user".

GIO also offers constants for these attribute values, which can be found by querying the GIO docs for G_FILE_ATTRIBUTE_* constants: https://docs.gtk.org/gio/index.html?q=G_FILE_ATTRIBUTE_

See docs.gtk.org for additional details.

Parameters:

  • attribute :  The GIO file info attribute to query for.
    type string
  • cb
    type function

Callback parameters:

  • type GLib.Error
  • type Gio.FileInfo
File:exists(cb) [src]
async
Check if the file exists.

Keep in mind that checking for existence before reading or writing a file is subject to race conditions. An external process may still alter a file between those two operations.

Also note that, due to limitations in GLib, this method cannot distinguish between a file that is actually absent and a file that the user has no access to.

Parameters:

  • cb
    type function

Callback parameters:

  • type GLib.Error
  • true if the file exists at its specified location.
    type boolean
File:size(cb) [src]
async
Query the size of the file.

Note that due to limitations in GLib, this will return 0 for files that the user has no access to.

Parameters:

  • cb
    type function

Callback parameters:

  • type GLib.Error
  • type number
File:type(cb) [src]
async
Query the type of the file.

Common scenarios would be to compare this against Gio.FileType.

Note that due to limitations in GLib, this will return Gio.FileType.UNKNOWN for files that the user has no access to.

Parameters:

  • cb
    type function

Callback parameters:

  • type GLib.Error
  • type Gio.FileType

Usage:

f:type(function(err, type)
    if err then return cb(err) end
    local is_dir = type == Gio.FileType.DIRECTORY
    local is_link = type == Gio.FileType.SYMBOLIC_LINK
    local is_file = type == Gio.FileType.REGULAR
    -- get a string representation
    print(Gio.FileType[type])
end)
File:create(cb) [src]
async
since v0.2.0
Creates an empty file.

Attempting to call this on an existing file will result in an error with type Gio.IOErrorEnum.EXISTS.

Do not use this when you intend to write to the file immediately after creation, as it is subject to race conditions. Write operations, such as file.write and file.write_stream create files when needed.

Parameters:

  • cb
    type function

Callback parameters:

  • type GLib.Error