6

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.

1
  • 2
    you could probably make a GET request to the file?! Commented Nov 2, 2018 at 14:08

4 Answers 4

6

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');
        })
      );
  }
Sign up to request clarification or add additional context in comments.

Comments

4

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)));
}

1 Comment

this will always return false, as it will always throw an error because it expects a json response, but receives a binary data
0

If the above answers didn't work for you (like myself) then try this. If the image doesn't exist it simply returns the default image path.

fileExists(id: number) {
    const folderPath = `../../assets/images/${id}.jpg`;

    this._http.get(folderPath, { responseType: 'text' }).toPromise().then(response => {
      this.imagePath = folderPath;
    }).catch(error => {
      return this.imagePath;
    });
}

Then in the html: <img class="" src="{{imagePath}}" />

Comments

0
import { Injectable } from '@angular/core'
import { HttpClient, HttpErrorResponse } from '@angular/common/http'
import { Observable, of } from 'rxjs'
import { catchError, map } from 'rxjs/operators'

@Injectable({ providedIn: 'root' })
export class FileService {

  constructor(private http: HttpClient) {}

  fileExists(url: string): Observable<boolean> {
    return this.http.get(url).pipe(
      map(() => true),
      catchError((err: HttpErrorResponse) => {
        const success: boolean = err.status.toString().startsWith('2')
        return of(success)
      })
    )
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.