【问题标题】:With gjs, how can I write Soup.Buffer chunks of data to a file?使用 gjs,如何将 Soup.Buffer 数据块写入文件?
【发布时间】:2013-08-30 04:52:27
【问题描述】:

我正在编写一个下载文件并将其写入磁盘的 GTK javascript 程序。这是我的代码的样子:

const Gio = imports.gi.Gio;
const Soup = imports.gi.Soup;

// start an http session to make http requests
let _httpSession = new Soup.SessionAsync();
Soup.Session.prototype.add_feature.call(_httpSession, new Soup.ProxyResolverDefault());

// open the file
let file = Gio.file_new_for_path(path);
let fstream = file.replace(null, false, Gio.FileCreateFlags.NONE, null);

// start the download
let request = Soup.Message.new('GET', url);
request.connect('got_chunk', Lang.bind(this, function(message, chunk){
  // write each chunk to file
  fstream.write(chunk, chunk.length, null);
}));

this._httpSession.queue_message(request, function(_httpSession, message) {
  // close the file
  fstream.close(null);
});

我在 fstream.write() 行收到错误:

    JS ERROR: !!!   Exception was: Error: Unhandled GType GCancellable unpacking GArgument from Number
    JS ERROR: !!!     message = '"Unhandled GType GCancellable unpacking GArgument from Number"'
    JS ERROR: !!!     fileName = '"./torbrowser-launcher"'
    JS ERROR: !!!     lineNumber = '402'
    JS ERROR: !!!     stack = '"([object _private_Soup_Message],[object _private_Soup_Buffer])@./torbrowser-launcher:402
("2.3.25-2")@./torbrowser-launcher:122
wrapper("2.3.25-2")@/usr/share/gjs-1.0/lang.js:204
("2.3.25-2")@/usr/share/gjs-1.0/lang.js:145
("2.3.25-2")@/usr/share/gjs-1.0/lang.js:239
@./torbrowser-launcher:489
"'

我能找到的对这个错误的唯一引用是在这个线程中:https://mail.gnome.org/archives/gnome-shell-list/2012-July/msg00126.html

那个人最终放弃并将他的代码移植到 python。

我也对“got_chunk”回调传递的内容感到困惑。 chunk 字段是一个 Soup.Buffer (http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Soup.Buffer.html)。我可以用 chunk.length 获得它的长度,但是当我尝试打印 chunk.data 时它是未定义的。当我只打印块时,它会打印:[object _private_Soup_Buffer]。

fstream 是一个 Gio.FileOutputStream (http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gio.FileOutputStream.html)。写入方法为:write(String buffer, guint32 count, Cancellable cancellable),cancellable是可选的。奇怪的是,如果我用这个替换写行,我仍然会得到完全相同的错误:

fstream.write('test ', 5, null);

【问题讨论】:

    标签: javascript gnome gjs


    【解决方案1】:

    我遇到了完全相同的问题。经过大量的试验和错误后,write() 调用归结为两个问题:

    1. 您使用的写函数的文档(http://www.roojs.com/seed/gir-1.2-gtk-3.0/gjs/Gio.FileOutputStream.html)似乎是错误的;写方法签名是(据我所知):

      write(String buffer, Cancellable cancellable, guint32 count)

    2. 但是,如果您只使用fstream.write(chunk, null, chunk.length);,您将写入一个全零的文件。我不知道为什么(与 GJS 绑定到底层 C 库的方式有关)但您应该使用 chunk.get_data() 而不仅仅是 chunk。 IE。将代码中的 write 调用替换为:

      fstream.write(chunk.get_data(), null, chunk.length);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-12
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2013-02-22
      • 2015-12-09
      • 2010-12-27
      • 2014-03-12
      相关资源
      最近更新 更多