UNPKG

file-state-monitor

Version:

Completely customizable file monitoring using states

86 lines (66 loc) 1.87 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _crypto = _interopRequireDefault(require("crypto")); var _fs = _interopRequireDefault(require("fs")); var _BaseFileState = _interopRequireDefault(require("./BaseFileState")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } class ContentHashState extends _BaseFileState.default { /** * Constructs a new content hash state * * @param {Object} fileInfo Object containing existing state data */ constructor(fileInfo) { super(fileInfo); if (Object.keys(fileInfo).length === 1) { this._sha1 = null; } } /** * Gets the SHA-1 hash of the file's content * * @return {string} SHA-1 content hash */ get sha1() { if (this._sha1 === null) { this._sha1 = this.computeSha1(); } return this._sha1; } /** * Computes the sha1 hash of the files content * * @return {string} Computed sha1 hash */ computeSha1() { let hash = _crypto.default.createHash('sha1'); hash.update(_fs.default.readFileSync(this.path)); return hash.digest('hex'); } /** * Checks if this file state is different than another by comparing their * SHA-1 content hashes * * @param {BaseFileState} otherState Other file state to check against * @return {Boolean} True if the two file states are different, false if not */ isDifferentThan(otherState) { if (this.path !== otherState.path) { throw new Error(`Can only compare files with the same path, but tried to compare ${this._path} with ${otherState.path}`); } return this.sha1 !== otherState.sha1; } /** * @inheritdoc */ toJson() { return { path: this.path, sha1: this.sha1 }; } } exports.default = ContentHashState;