FoalTS / foal

Full-featured Node.js framework, with no complexity. 🚀 Simple and easy to use, TypeScript-based and well-documented.
https://foalts.org/
MIT License
1.89k stars 139 forks source link

Read file and convert it to base64 string #812

Closed Majunko closed 3 years ago

Majunko commented 3 years ago

Hello,

i'm currently working this FoalTS and Angular, so i would like that FoalTS has a function that allows read a file with the actual function read() and create another function to convert this file readed to base64.

I made this with the next code:

import * as fs from 'fs';
import import { join } from 'path';
import { Config } from '@foal/core';

const directory = Config.getOrThrow(
        'settings.disk.local.directory',
        'string',
        'You must provide a directory name when using local file storage (LocalDisk).'
);

const fullPath = join(directory, 'users/profile_photo.png')

const binaryData = fs.readFileSync(fullPath);
const base64String = Buffer.from(binaryData).toString('base64');
console.log(base64String);

I don't know if there is a better way to do this, but this is what i need when i read many users with his profile photos. Regards.

hashtd commented 3 years ago

@Majunko

assuming user.enitry.ts User modal is in use, where you can create simple method profilePicAsDataString which in case wrap your logic.

this use case is not directly useful at framework core, its more like application level utility

Majunko commented 3 years ago

No problem, i created a service with 2 functions to make this.

getPathLocalDisk(path: string): string {
  const directory = Config.getOrThrow(
    'settings.disk.local.directory',
    'string',
    'You must provide a directory name when using local file storage (LocalDisk).'
  );
  return join(directory, path);
}

fileToBase64(file: string): string {
  try {
    const binaryData = fs.readFileSync(this.getPathLocalDisk(file));
    const base64String = Buffer.from(binaryData).toString('base64');
    return base64String;
  } catch (e) {
    console.error(e);
  }
  return '';
}

So i call it like this:

const users = await getRepository(User)
  .createQueryBuilder('user')
  .select(['user.id', 'user.name', 'user.email', 'user.profile_photo'])
  .getMany();

users.forEach(element => {
  element['profilePhotoB64'] = this.myService.fileToBase64(element.profile_photo);
});
LoicPoullain commented 3 years ago

@Majunko why not using the Disk service directly?

class FileService {

  @dependency
  disk: Disk;

  async readFile() {
    const { file, size } = await this.disk.read('avatars/xxx.jpg', 'buffer');
    return file.toString('base64');
  }

}
Majunko commented 3 years ago

My mistake, more simple and readable. It works pretty well.

Thank you so much for your reply.