Javascript 使用gjs,如何将Soup.Buffer数据块写入文件?
我正在编写一个GTK javascript程序,下载一个文件并将其写入磁盘。我的代码是这样的:Javascript 使用gjs,如何将Soup.Buffer数据块写入文件?,javascript,gnome,gjs,Javascript,Gnome,Gjs,我正在编写一个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
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()行中遇到错误:
我能找到的对此错误的唯一引用是在以下线程中:
那个人最终放弃了将代码移植到python
我还对“got_chunk”回调传递的内容感到困惑。chunk字段是一个Soup.Buffer()。我可以通过chunk.length获得它的长度,但当我尝试打印chunk.data时,它是未定义的。当我只打印块时,它会打印:[对象_私有_汤_缓冲区]
fstream是Gio.FileOutputStream()。写入方法为:写入(字符串缓冲区、guint32计数、可取消),可取消为可选。奇怪的是,如果我用这个替换写行,我仍然会得到完全相同的错误:
fstream.write('test ', 5, null);
我遇到了完全相同的问题。经过大量的尝试和错误,它归结为
write()
调用的两个问题:
写入(字符串缓冲区、可取消、几内亚32计数)
fstream.write(chunk,null,chunk.length)代码>您将编写一个满是零的文件。我不知道为什么(这与GJS绑定到底层C库的方式有关),但您应该使用chunk.get_data()
而不仅仅是chunk
。即,将代码中的写调用替换为:
fstream.write(chunk.get_data(),null,chunk.length)代码>
fstream.write('test ', 5, null);