我正在编写一个下载文件并将其写入磁盘的 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”回调传递的内容感到困惑。块字段是一个 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方法为:write(String buffer, guint32 count, Cancellable cancellable),cancellable是可选的。奇怪的是,如果我用这个替换写行,我仍然会得到完全相同的错误:
fstream.write('test ', 5, null);