Including node groups into addon

I am currently trying to include some premade node groups from a blend file in my addon, and I haven’t quite found any proper way to do it. I just have a blend file and I would like to import all the nodegroups in it when the addon is installed. What is the proper way to do this?

currently I have this, although Im not sure how I would make a loop to iterate and append all the node groups in the file

class NG_OT_Append(Operator):
    bl_idname = "ng.append_node_tree"
    bl_label = "Append NG"
    bl_options = {'REGISTER'}

    
    def execute(self, context):

        USER = Path(resource_path('USER'))
        ADDON = "PaintKit_build_1_0_0"
        BlendPath = "PK_Asset_1_0_0"
        blendFile = USER / "scripts/addons" / ADDON / "assets" / BlendPath + '.blend'
        section   = "\\NodeTree\\"

        filepath  = blendfile + section + object
        directory = blendfile + section
        bpy.ops.wm.append(filepath=filepath, filename=filename, directory=directory)

Instead of bpy.ops.wm.append try to use bpy.data.libraries.load

with bpy.data.libraries.load(filepath=filepath, link=False) as (data_from, data_to):
    data_to.node_groups = data_from.node_groups

https://docs.blender.org/api/4.0/bpy.types.BlendDataLibraries.html#bpy.types.BlendDataLibraries.load

And if you wanna export node groups to external file, I assume you should use libraries.write

https://docs.blender.org/api/4.0/bpy.types.BlendDataLibraries.html#bpy.types.BlendDataLibraries.write

Thank you! And no need to export to external, I just need to be able to package the blend file I have with them into the addon. Do you have any idea how I could for loop over all the groups in the blender file I want to load?

In case of library.load with data_to.node_groups = data_from.node_groups you will append all the node groups from filepath: shaders and geo-nodes. Like if you manually click append and select all the nodes in *.blend/node_tree.

You can specify groups by name list
data_to.node_groups = ['fancy_shader', 'not_so_fancy_shader', 'cool_geo_nodes']


But I think the best practice for such task is to use asset browser.
Make assets from your nodes and add new asset catalog with

bpy.ops.preferences.asset_library_add(directory=file_dir)

I’m not into this topic, but should work