GJS同步读取文件

时间:2013-04-12 13:12:42

标签: javascript file-io synchronous gjs

我正在尝试更准确地使用GJS 以同步方式读取文本文件。 以下是文件读取的异步函数

的示例

gio-cat.js 我找到了如何使用下一个函数继续种子:

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;
}

但不幸的是,它不适用于GJS。 任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:1)

当我使用GJS开发Cinnamon applet时,我曾经使用get_file_contents_utf8_sync函数来读取文本文件:

const Cinnamon = imports.gi.Cinnamon;

let fileContent = Cinnamon.get_file_contents_utf8_sync("file path");

如果您安装了肉桂并且您同意使用它,它会回答您的问题 否则这里是get_file_contents_utf8_sync函数的C代码,希望这对你有所帮助:

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

答案 1 :(得分:1)

这是一个只适用于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;
}

答案 2 :(得分:1)

GLib具有辅助函数GLib.file_get_contents(String fileName)来同步读取文件:

const GLib = imports.gi.GLib;
//...
let fileContents = String(GLib.file_get_contents("/path/to/yourFile")[1]);

答案 3 :(得分:0)

尝试替换

new gio.DataInputStream.c_new(fstream);

gio.DataInputStream.new(fstream);

它对我有用

相关问题