Search code examples
jsonfiledownloadnestjsfs

NestJs - How do I download objects as json files locally?


So I have my NestJs application connected to mongoDB/Mongoose. I'd like to get everything in the repository and save it locally on my computer as a json file. Could anyone advise how to go about that?

backup.service.ts

@Injectable()
export class BackupService {
  constructor(private userService: UserService) {}

  private async getUsers(): Promise<User[]> {
    return await this.shiftService.getMany();
  }

  public async downloadUserData() {
      const users = await this.getUsers();
      // next step to download as json file to local computer?

  }
}

Any advice would be greatly appreciated!


Solution

  • You'll need to write the data to a file using Node's fs module. You'll be able to do something like this:

    import { writeFile } from 'fs/promises';
    import { join } from 'path';
    
    @Injectable()
    export class BackupService {
      constructor(private userService: UserService) {}
    
      private async getUsers(): Promise<User[]> {
        return await this.shiftService.getMany();
      }
    
      public async downloadUserData() {
          const users = await this.getUsers();
          await writeFile(join(process.cwd(), 'db', 'users.json'), JSON.stringify(users));
      }
    }
    

    This should write the data to a JSON file at <projectRoot>/db/users.json. Keep in mind this is a direct write and not an append, so any data there will be overwritten.