Tried to count the number of links without associated files.

Hello everyone,
I tried writing code, with dataview, to count the number of links without associated files, and then display them with their source file. But it doesn’t seem to work.
Do you have a solution?

// Create a map: key = broken link, value = array of source files
let brokenLinksMap = new Map();

// Browse all pages
for (let page of dv.pages()) {
    if (!page.file || !page.file.links) continue;

    for (let link of page.file.links) {
        const target = link.path;

        // Checks if the target page exists
        if (!dv.page(target)) {
            // If this broken link is not yet in the map, initialize it
            if (!brokenLinksMap.has(target)) {
                brokenLinksMap.set(target, []);
            }
            // Adds the source file to the list
            brokenLinksMap.get(target).push(page.file.name);
        }
    }
}

// Convert to table and sort by missing link name
const brokenArray = Array.from(brokenLinksMap.entries()).sort((a, b) => a[0].localeCompare(b[0]));

// Display
if (brokenArray.length === 0) {
    dv.paragraph("✅ No link to a non-existent note found.");
} else {
    dv.paragraph(`🧩 **${brokenArray.length}** missing files, referenced in  :`);

    // Display as a grouped list
    for (let [missingNote, sources] of brokenArray) {
        dv.header(4, `🔗 [[${missingNote}]]`);
        dv.list(sources.map(src => `[[${src}]]`));
    }
}

Is this pure ChatGPT stuff? Why do you believe file.links is a thing?

And what is it you’re really trying to get done?

I believe they’re just looking for orphaned files.

list
from ""
where length(file.inlinks) = 0 and length(file.outlinks) = 0

Shows notes that have zero links in or out. If you just want notes that aren’t linked from anywhere, drop the outlinks part.

It sounds to me more like they’re looking for links that don’t point to any file.

1 Like

Perhaps useful? → Is there a way to see backlinks without creating a markdown document? - #3 by JLDiaz

The link above shows all non-existing pages that are referenced from other notes. For each non-existing page, a list of links to the notes that refer to it is presented.

Or perhaps you are looking for the opposite: a list of all notes that contain links to non-existing notes.

The following code will provide this (the table is sorted in descending order of broken links):

```dataviewjs
const data = dv.app.metadataCache.unresolvedLinks;

const rows = Object.entries(data)
    .map(([path, links]) => ({ path, count: Object.keys(links).length }))
    .filter(item => item.count > 0)
    .sort((a, b) => b.count - a.count);

dv.table(["Note", "Broken links"],
    rows.map(item => [dv.fileLink(item.path), item.count]));
```