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.
48 lines (40 loc) • 1.49 kB
JavaScript
const os = require('os');
const totalMemory = os.totalmem();
const options = require('./options')
class MemoryMonitor {
static get options() { return options }
constructor() {
this.filesWithContent = new Set()
}
get freeMemoryPercentage() { return (os.freemem() / totalMemory) * 100 }
get isMemOk() { return this.freeMemoryPercentage > options.thresholdPercentage }
add(file) {
this.filesWithContent.add(file)
this.clear()
}
clear(force=false) {
if (!force && this.isMemOk) return
const now = Date.now()
if(this.lastClear && (now - this.lastClear) < 1000) return
this.lastClear = now
let count = 0
for (const file of this.filesWithContent) {
if(this.isMemOk && !force) break
const rating = this.calculateRating(file)
if(file.age > options.maxStoreTime || rating < options.thresholdRating) {
delete file._buffer
this.filesWithContent.delete(file)
count++
}
}
if(count) options.logger.warn(`The memory is full. The content for ${count} files was removed. `)
}
calculateRating(file) {
const { accessCount, lastAccess, size } = options.weights
return accessCount * file.accessCount + lastAccess * file.age + size * file.meta.size
}
remove(...files) {
files.forEach(file => this.filesWithContent.delete(file))
}
}
module.exports = MemoryMonitor;