I'm trying to use GJS and more precisely to read a text file in a synchronous way. Here is an example an the asynchronous function for file reading
gio-cat.js I found how to proceed with seed using the next function:
function readFile(filename) {
print(filename);
var input_file = gio.file_new_for_path(filename);
var fstream = input_file.read();
var dstream = new gio.DataInputStream.c_new(fstream);
var data = dstream.read_until("", 0);
fstream.close();
return data;
}
but unfortunately, it doesn't work with GJS. Can anyone help me ?
GLib has the helper function GLib.file_get_contents(String fileName) to read files synchronously:
const GLib = imports.gi.GLib;
//...
let fileContents = String(GLib.file_get_contents("/path/to/yourFile")[1]);
Here is a solution that works with just Gio.
function readFile(filename) {
let input_file = Gio.file_new_for_path(filename);
let size = input_file.query_info(
"standard::size",
Gio.FileQueryInfoFlags.NONE,
null).get_size();
let stream = input_file.open_readwrite(null).get_input_stream();
let data = stream.read_bytes(size, null).get_data();
stream.close(null);
return data;
}
As I use GJS for developing Cinnamon applets, I used to use the get_file_contents_utf8_sync
function to read text files :
const Cinnamon = imports.gi.Cinnamon;
let fileContent = Cinnamon.get_file_contents_utf8_sync("file path");
If you have Cinnamon installed and you agree to use it, it answers your question.
Otherwise here is the C code of the get_file_contents_utf8_sync
function in cinnamon-util.c
, hoping this will help you:
char * cinnamon_get_file_contents_utf8_sync (const char *path, GError **error)
{
char *contents;
gsize len;
if (!g_file_get_contents (path, &contents, &len, error))
return NULL;
if (!g_utf8_validate (contents, len, NULL))
{
g_free (contents);
g_set_error (error,
G_IO_ERROR,
G_IO_ERROR_FAILED,
"File %s contains invalid UTF-8",
path);
return NULL;
}
return contents;
}
Cinnamon source code
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With