File corruption on file.replace_contents_async
I might be holding this wrong but I haven’t been able to find any documentation on how to properly use replace_contents_async
. Currently, if I read from a file using load_contents_async
and, afterwards, try to replace its contents using replace_contents_async
, the file ends up corrupted.
Below is a isolated example and instructions that reproduce the issue.
To reproduce:
- Save the code, below, to app.js.
echo 'Original text' > test.txt
gjs ./app.js
What should happen
The contents of the text file should be updated to read 'Hello, new text!'.
What actually happens
The file is corrupted.
Code
#!/usr/bin/gjs
imports.gi.versions.Gtk = '3.0'
const Gtk = imports.gi.Gtk
const GLib = imports.gi.GLib
const Gio = imports.gi.Gio
class App {
constructor () {
this.application = new Gtk.Application()
this.application.hold()
this.activate = () => {
// Read file.
let file = Gio.File.new_for_path('./test.txt')
file.load_contents_async(null, (file, task) => {
let success, contents, entityTagLocation, error
try {
;[success, contents, entityTagLocation, error] = file.load_contents_finish(task)
if (!success) {
print(error)
application.quit()
}
print(contents.toString())
// Replace contents of file.
file.replace_contents_async (
/* contents: */ 'Hello, new text! :)',
/* etag: */ null,
/* make_backup: */ true,
/* flags: */ Gio.FileCreateFlags.NONE,
/* cancellable: */ null,
/* callback: */ (file, task) => {
try {
let [success, newETag, error] = file.replace_contents_finish(task)
this.application.quit()
} catch (error) {
print(error)
this.application.quit()
}
}
)
} catch (error) {
print(error)
application.quit()
}
})
}
this.application.connect('activate', this.activate)
}
}
const app = new App()
app.application.run(ARGV)
Environment
- GLib version: 2.56.1
- GJS version: 1.52.1
- Gnome Shell version: 3.28.2
- OS: Pop!_OS 18.04