Check if a file exists

Check the existence of a file in Nextcloud via file path

Script nextcloud

by nextcloud ยท 2/20/2025

  • Submitted by nextcloud Bun
    Created 86 days ago
    1
    import axios from "axios";
    2
    
    
    3
    export async function main(
    4
        nextcloud: RT.Nextcloud,
    5
        path: string,
    6
    ) {
    7
    
    
    8
        const res = await axios.head(
    9
            `${nextcloud.baseUrl}/remote.php/dav/files/${nextcloud.userId}/${path}`,
    10
            {
    11
                auth: {
    12
                    username: nextcloud.userId,
    13
                    password: nextcloud.token,
    14
                },
    15
                validateStatus: function (status) {
    16
                    return status < 500; // Reject only if status code is 500 or greater
    17
                }
    18
            }
    19
        );
    20
        if (Math.round(res.status / 100) === 4) {
    21
            if (res.status !== 404) {
    22
                throw new Error('Error ' + res.status)
    23
            }
    24
        }
    25
        return res.status === 200// file exists
    26
    }
    27
    
    
    28