0

I have managed to read the content of a file from the disk with this snippet:

const { Gio } = imports.gi;   

class Indicator extends PanelMenu.Button {                                                                                                                     
 
   _init() {                                                                                                                                                  
        const file = Gio.File.new_for_uri(                                                                                                                     
             'file:.config/wireguard/current_vpn');
        const [, contents, etag] = this._file.load_contents(null);
        const decoder = new TextDecoder('utf-8');
        const contentsString = decoder.decode(contents);
    }
}

Now I am tryning to list all the *.conf files from a directory. But I cannot find a proper way to do that reading the Gio docs

pietrodito
  • 1,783
  • 15
  • 24

2 Answers2

1

You'll have to enumerate the files in the directory and perform your comparison on the file names as you go. There are examples of enumerating files in the File Operations guide on gjs.guide:

const {GLib, Gio} = imports.gi;

const directory = Gio.File.new_for_path('.');

const iter = await new Promise((resolve, reject) => {
    directory.enumerate_children_async(
        'standard::*',
        Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS,
        GLib.PRIORITY_DEFAULT,
        cancellable,
        (file_, result) => {
            try {
                resolve(directory.enumerate_children_finish(result));
            } catch (e) {
                reject(e);
            }
        }
    );
});

while (true) {
    const infos = await new Promise((resolve, reject) => {
        iter.next_files_async(
            10, // max results
            GLib.PRIORITY_DEFAULT,
            null,
            (iter_, res) => {
                try {
                    resolve(iter.next_files_finish(res));
                } catch (e) {
                    reject(e);
                }
            }
        );
    });

    if (infos.length === 0)
        break;
        
    for (const info of infos)
        log(info.get_name());
}
andy.holmes
  • 3,383
  • 17
  • 28
0

The apparently correct answer of andy.hollmes made me sick. This is for a very personnal tool with no sharing purpose, so I am gonna use this trick with bash command (thanks to this answer):

var files_string = GLib.spawn_command_line_sync(                                                                                                       
    "ls /this/is/a/directory/*.conf")[1].toString().trim();

For those who will use the same approach, I have noticed that the absolute path is needed for me. Yet I have read that the extension runs in the user directory...

pietrodito
  • 1,783
  • 15
  • 24