UNPKG

als-path-tree

Version:

A Node.js library for managing a virtual file system structure, offering functionalities for file and directory operations with a shared storage system.

76 lines (64 loc) 2.33 kB
const Item = require('./item') class File extends Item { constructor(name, meta, parent, content) { super(name, parent, true) if (parent) parent.files[name] = this this.meta = {} this.save(content) this.meta = this.prepareMeta(meta); this.accessCount = 0; } prepareMeta(meta = {}) { return { mtimeMs: meta.mtimeMs || Date.now(), atimeMs: meta.atimeMs || Date.now(), size: meta.size || (this._buffer ? this._buffer.length : 0) }; } get buffer() { this.accessCount++ return this._buffer } save(value) { if(value === null || value === undefined) { this._buffer = null this.meta.size = 0 this.main.memMonitor.remove(this) return } const buffer = this.compare(value) if (buffer === false) return this._buffer = value this.meta.size = this._buffer.length this.accessCount++ this.main.memMonitor.add(this) } compare(content) { const isBuffer = Buffer.isBuffer(content); const isString = typeof content === 'string' if(!isBuffer && !isString) return false if(isString) content = Buffer.from(content) if (Buffer.isBuffer(this._buffer) && Buffer.compare(this._buffer, content) === 0) return false; return content } get lastAccessTime() { return this.meta.atimeMs || this.meta.mtimeMs; } get age() { return (Date.now() - this.lastAccessTime) / (1000 * 60 * 60); } // Возраст в часах get content() { return this._buffer ? this.buffer.toString() : null } get json() { return this._buffer ? JSON.parse(this.content) : null } delete() { if (!this.parent) return delete this.parent.files[this.name] this.main.memMonitor.remove(this) this.parent.removeIfEmpty() } copyTo(destPath) { this.root.addFile(destPath, { size: this.size }, this.buffer) } moveTo(destPath) { if(!this.parent) return const { parts, filename } = this.splitPath(destPath) const newParent = this.root.addDir(parts) if(newParent === this.parent) this.rename(destPath) newParent.files[filename] = this this.name = filename } } module.exports = File