Write to a file from gnome extension

In order to write to a file from the gnome extension, I use replace_contents_bytes_async, as in the example here File Operations | GNOME JavaScript

extension.js:

import { Extension } from 'resource:///org/gnome/shell/extensions/extension.js';
import GLib from 'gi://GLib';
import Gio from 'gi://Gio';

export default class ExampleExtension extends Extension {
async enable() {      
    const file = Gio.File.new_for_path('/tmp/test-file.txt');
    const bytes = new GLib.Bytes('some file contents');

    const [etag] = await file.replace_contents_bytes_async(bytes, null, false,
        Gio.FileCreateFlags.REPLACE_DESTINATION, null);
}

disable() {
}
}

But this code gives an error:

Judging by the documentation, replace_contents_bytes_async should also accept a callback Gio.File.replace_contents_bytes_async :

    const [etag] = await file.replace_contents_bytes_async(bytes, null, false,
        Gio.FileCreateFlags.REPLACE_DESTINATION, null, function(source_object, res, data){});

But this code also gives an error:
2

What shell version are you targetting?

You may need to use Gio._promisify(Gio.File.prototype, 'replace_contents_bytes_async'); first in order to use it as an async function.

The version is GNOME Shell 46.0

I changed to

    Gio._promisify(Gio.File.prototype, 'replace_contents_bytes_async');
    const [etag] = await file.replace_contents_bytes_async(bytes, null, false,
        Gio.FileCreateFlags.REPLACE_DESTINATION, null);

New error:
3
@marcotrevi

Gio._promisify(Gio.File.prototype, ‘replace_contents_bytes_async’);

Use

Gio._promisify(Gio.File.prototype,
    'replace_contents_bytes_async', 'replace_contents_finish');

In this particular case, the name of the “finish” function is too different to be determined automatically, so you have to specify it explicitly.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.