Angular - How to check if file exists without fs

14,849

Solution 1

Thank you, scipper. Yes, that's the way I manage it now. But I hoped there would be a easier, one-line function to check this.

Here the code (it returns the folder, not the file, so I can use it fore more purposes):

getFolder(subFolder: string): Observable<string> {
    const folderPath = `assets/folder/${subFolder.toLocaleUpperCase()}`;
    return this.httpClient
      .get(`${folderPath}/file.png`, { observe: 'response', responseType: 'blob' })
      .pipe(
        map(response => {
          return folderPath;
        }),
        catchError(error => {
          return of('assets/folder/default');
        })
      );
  }

Solution 2

Here's a snippet that returns a boolean Observable for whether or not a file exists at a given URL:

fileExists(url: string): Observable<boolean> {
    return this.httpClient.get(url)
        .pipe(
            map(response => {
                return true;
            }),
            catchError(error => {
                return of(false);
            })
        );
}

Or, the same thing but in a more concise, one-line format:

public fileExists(url: string): Observable<boolean> {
    return this.httpClient.get(url).pipe(map(() => true), catchError(() => of(false)));
}
Share:
14,849
MatterOfFact
Author by

MatterOfFact

B. Sc. Wirtschaftsinformatik (business informatics) web application developer (dotnet core, .Net, Angular)

Updated on June 27, 2022

Comments

  • MatterOfFact
    MatterOfFact about 2 years

    As fs seems not to work anymore since Angular 6 I haven't found an alternative way to check if a file exists. In my special case I have to check if a specific image file exists in the assets folder, e.g. something like this:

    if (fileExists('path')) { doSomething(); }
    

    I've tried to install the file-exists package but this uses

    const fs = require('fs')
    const path = require('path')
    

    which apparently is not supported by Angular 7.

    Is there anybody who can help? Thanks a lot.