import * as plugins from './smartbucket.plugins'; import { Directory } from './smartbucket.classes.directory'; export interface IFileMetaData { name: string; fileType: string; size: string; } export class File { // STATIC public static async createFileFromString( dirArg: Directory, fileName: string, fileContent: string ) { await this.createFileFromBuffer(dirArg, fileName, Buffer.from(fileContent)); } public static async createFileFromBuffer( directoryRef: Directory, fileName: string, fileContent: Buffer ) { const filePath = plugins.path.join(directoryRef.getBasePath(), fileName); const streamIntake = new plugins.streamfunction.Intake(); const putPromise = directoryRef.bucketRef.smartbucketRef.minioClient .putObject(this.name, filePath, streamIntake.getReadable()) .catch(e => console.log(e)); streamIntake.pushData(fileContent); streamIntake.signalEnd(); await putPromise; } // INSTANCE public directoryRef: Directory; public path: string; public metaData: IFileMetaData; constructor(directoryRefArg: Directory, fileName: string) { this.directoryRef = directoryRefArg; } public async getContentAsString() { const fileBuffer = await this.getContentAsBuffer(); return fileBuffer.toString(); } public async getContentAsBuffer() { const done = plugins.smartpromise.defer(); const fileStream = await this.directoryRef.bucketRef.smartbucketRef.minioClient .getObject(this.directoryRef.bucketRef.name, this.path) .catch(e => console.log(e)); let completeFile = new Buffer(''); const duplexStream = plugins.streamfunction.createDuplexStream( async chunk => { completeFile = Buffer.concat([chunk]); return chunk; }, async cb => { done.resolve(); return Buffer.from(''); } ); if (!fileStream) { return null; } fileStream.pipe(duplexStream); await done.promise; return completeFile; } public async streamContent() { throw new Error('not yet implemented'); // TODO } /** * removes this file */ public async remove() { await this.directoryRef.bucketRef.smartbucketRef.minioClient.removeObject( this.directoryRef.bucketRef.name, this.path ); await this.directoryRef.listFiles(); } }