Search code examples
typescriptfsangular7

Angular - How to check if file exists without fs


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.


Solution

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