Skip to content

Instantly share code, notes, and snippets.

@fhpriamo
Created July 9, 2020 18:16
Show Gist options
  • Save fhpriamo/332f3447b5d4b9da1754e9fcfe017a71 to your computer and use it in GitHub Desktop.
Save fhpriamo/332f3447b5d4b9da1754e9fcfe017a71 to your computer and use it in GitHub Desktop.
import { createHash } from 'crypto';
import fs from 'fs';
import { basename } from 'path';
/**
* An abstraction for a buffered file suitable to be used
* in tests (specially upload tests).
*
* Buffering and digesting are deffered until they are used.
*/
export class DeferredFileBuffer {
constructor(path, metadata = {}) {
Object.defineProperties(this, {
_path: {
value: path,
enumerable: false,
writable: false,
configurable: false,
},
meta: {
value: { path, filename: basename(path), ...metadata },
enumerable: true,
writable: false,
configurable: false,
},
_buffer: {
enumerable: false,
writable: true,
configurable: false,
},
_md5: {
enumerable: false,
writable: true,
configurable: false,
},
});
}
/**
* Buffers the file into memory and returns the buffered content.
*
* @returns Buffer
*/
read() {
if (Buffer.isBuffer(this._buffer)) return this._buffer;
this._buffer = fs.readFileSync(this._path);
return this._buffer;
}
/**
* Returns the file buffer.
*
* @returns Buffer
*/
get buffer() {
return this.read();
}
/**
* The file md5 digest.
*
* (Implies the buffering of the file)
*
* @returns string
*/
get md5() {
if (typeof this._md5 === 'string') return this._md5;
this._md5 = createHash('md5').update(this.buffer).digest('hex');
return this._md5;
}
/**
* The file size in bytes.
*
* (Implies the buffering of the file)
*
* @returns number
*/
get size() {
return this.buffer.byteLength;
}
/**
* Makes the buffered memory elegible to be freed.
*/
free() {
this._buffer = undefined;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment