title: Observables in nestjs - Reading a file asynchronously
body: <p>I am trying a use case of reading a json file asynchronously and sending it out as a response (as a rxjs observable data). Here is the service that I use</p>
  
  <pre><code> import { logger } from './../../shared/utils/logger';
  import { Injectable } from '@nestjs/common';
  import * as fs from 'fs';
  import * as path from 'path';
  import { BehaviorSubject, Observable, pipe, of, from, throwError, merge} from 'rxjs';
  import { map, filter, scan, take, debounce, switchMap, retry, catchError, mergeMap, delay, zip, tap, mapTo } from 'rxjs/operators';
  import { HttpResponseModel } from '../model/config.model';
  import { isNullOrUndefined } from 'util';
  @Injectable()
  export class NewProviderService {
      serviceSubject: BehaviorSubject&lt;HttpResponseModel[]&gt;;
      filePath: string;
      httpResponseObjectArray: HttpResponseModel[];
      constructor() {
          this.serviceSubject = new BehaviorSubject&lt;HttpResponseModel[]&gt;([]);
          this.filePath = path.resolve(__dirname, './../../shared/assets/httpTest.json');
          this.setSubject();
      }
  
  
   readFileFromJSON() {
        this.readFileFromJsonSync();
        fs.exists(this.filePath.toString(), exists =&gt; {
          if (exists) {
             fs.readFile(this.filePath.toString(), 'utf-8', (err, data) =&gt; {
                  logger.info('file read without parsin', data);
                  this.httpResponseObjectArray = JSON.parse(data).HttpTestResponse;
                  logger.info('array obj is:', this.httpResponseObjectArray);
                  logger.info('file read after parsing', JSON.parse(data));
                  return this.httpResponseObjectArray;
              });
          } else {
              return null;
          }
  
      });
  }
  
  
  getObservable(): Observable&lt;HttpResponseModel[]&gt; {
         // create an observable
          // return Observable.create(observer =&gt; {
          //     observer.next(this.readFileFromJSON());
          // });
  
          return of(this.readFileFromJsonSync()).pipe(map(data =&gt; {
              logger.info('inside obs methid', data);
              return data;
          }));
  
      }
  
      setSubject() {
          this.getObservable().subscribe(data =&gt; {
              logger.info('data before setting in sub', data);
              this.serviceSubject.next(data);
          });
      }
  }
  </code></pre>
  
  <p>So I wanted to subscribe to this emitted observable in the controller, but the values are getting read after I have subscribed and read the subject (<code>BehaviorSubject</code>). I understand that I am kind of doing something wrong with the subscription and emitting of data, but couldn't understand where I am doing wrong. Every time the controller prints <strong>'data subscribed undefined'</strong> and then continues to read the file and emit the observable</p>
  
  <p>This is the controller data</p>
  
  <pre><code>@Get('/getJsonData')
    public async getJsonData(@Req() requestAnimationFrame, @Res() res) {
      this.newService.serviceSubject.subscribe(data =&gt; {
        logger.info('data subscribed', data);
        res.status(HttpStatus.OK).send(data);
      });
  
    }
  </code></pre>
  
  <p>It works well if I read the file synchronously</p>
  
  <p>replace <code>readFileFromJSON()</code> with the following method and it works well</p>
  
  <pre><code>readFileFromJsonSync(): HttpResponseModel[] {
          const objRead = JSON.parse(fs.readFileSync(this.filePath.toString(), {encoding: 'utf-8'}));
          logger.info('object read is', objRead.HttpTestResponse);
          return objRead.HttpTestResponse;
  
      }
  </code></pre>
  
  <p>So I am missing something while reading the file async. I am not sure what am I doing wrong. Could someone please help?</p>