/**
 * Copyright (c) 2020, 2021 Oracle and/or its affiliates.  All rights reserved.
 * This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
 */ import { statSync , createReadStream , readFileSync } from "fs" ; import { Readable } from "stream" ; import { createHash } from "crypto" ; import { UploadableBlob } from "./uploadable-blob" ; export class NodeFSBlob implements UploadableBlob { size : number ; type : string = "" ; private readonly start : number ; private readonly end : number ; private readonly fileSize : number ; public constructor ( private readonly filePath , private readonly highWaterMark , start ? , end ? , fileSize ? ) { this . fileSize = fileSize || statSync ( this . filePath ) . size ; this . start = start || 0 ; this . end = end || this . fileSize ; if ( this . end > this . fileSize ) { this . end = this . fileSize ; } this . size = this . end - this . start ; } public async getData ( ) { const end = this . fileSize === 0 ? this . end : this . end - 1 ; return createReadStream ( this . filePath , { start : this . start , end : end , highWaterMark : this . highWaterMark } ) ; } public slice ( start ? , end ? , contentType ? ) { return new NodeFSBlob ( this . filePath , this . highWaterMark , start , end , this . fileSize ) ; } public async getMD5Hash ( ) { return new Promise ( async ( resolve ) => { const md5Hash = createHash ( "md5" ) ; const dataStream = await this . getData ( ) ; dataStream . on ( "data" , data => md5Hash . update ( data ) ) . on ( "end" , ( ) => resolve ( md5Hash . digest ( "base64" ) ) ) ; } ) ; } public async arrayBuffer ( ) { return new Promise ( resolve => { resolve ( readFileSync ( this . filePath ) ) ; } ) ; } public async text ( ) { const data = await this . getData ( ) ; return this . streamToString ( data ) ; } public async streamToString ( stream ) { const chunks = [ ] ; return new Promise ( ( resolve , reject ) => { stream . on ( "data" , chunk => chunks . push ( chunk ) ) ; stream . on ( "error" , reject ) ; stream . on ( "end" , ( ) => resolve ( Buffer . concat ( chunks ) . toString ( "utf8" ) ) ) ; } ) ; } public stream ( ) { throw "ReadableStream not supported in NodeJs. Use getData() to fetch Stream" ; } }