Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GJS read file synchronously

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 ?

like image 701
Baptiste Mazin Avatar asked Apr 12 '13 13:04

Baptiste Mazin


3 Answers

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]);
like image 198
Daniel Avatar answered Oct 13 '22 18:10

Daniel


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;
}
like image 40
ABP Avatar answered Oct 13 '22 17:10

ABP


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

like image 1
Nicolas Avatar answered Oct 13 '22 18:10

Nicolas