You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
95 lines
2.1 KiB
95 lines
2.1 KiB
import { readdir, stat } from 'fs/promises'
|
|
import dayjs from 'dayjs'
|
|
|
|
/**
|
|
* getting files
|
|
*
|
|
* @author Björn Hase
|
|
* @license hhttps://www.gnu.org/licenses/gpl-3.0.en.html GPL-3
|
|
* @link https://gitea.node001.net/HerrHase/tellme-bot.git
|
|
*
|
|
*/
|
|
class File {
|
|
|
|
/**
|
|
*
|
|
* @param {string} path
|
|
*
|
|
*/
|
|
constructor(path) {
|
|
this.path = path
|
|
}
|
|
|
|
/**
|
|
* getting alle files from
|
|
*
|
|
* @param {string} path
|
|
* @return {object}
|
|
*
|
|
*/
|
|
async get() {
|
|
|
|
const result = {
|
|
files: [],
|
|
errors: false
|
|
}
|
|
|
|
const files = []
|
|
|
|
try {
|
|
const files = await readdir(this.path, {
|
|
withFileTypes: true
|
|
})
|
|
|
|
// run through all files, add options
|
|
for (const file of files) {
|
|
|
|
// getting meta
|
|
const meta = await stat(this.path + '/' + file.name)
|
|
|
|
result['files'].push({
|
|
name: file.name,
|
|
is_directory: file.isDirectory(),
|
|
size: this.formatBytes(meta.size),
|
|
created_at: dayjs(meta.ctime).format('DD.MM.YYYY HH:mm'),
|
|
updated_at: dayjs(meta.mtime).format('DD.MM.YYYY HH:mm')
|
|
})
|
|
}
|
|
|
|
result['files'].sort(function(a, b) {
|
|
if (a.is_directory) {
|
|
return -1
|
|
} else {
|
|
return 0
|
|
}
|
|
})
|
|
} catch (error) {
|
|
result['error'] = error
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
/**
|
|
* getting size of file
|
|
*
|
|
* @param float size
|
|
* @param integer precision
|
|
* @return string
|
|
*/
|
|
formatBytes(size) {
|
|
|
|
if (size === 0) {
|
|
return '0 bytes'
|
|
}
|
|
|
|
// getting base of size
|
|
const base = Math.log(size) / Math.log(1024);
|
|
const suffixes = ['Bytes', 'KB', 'MB', 'G', 'T']
|
|
|
|
return Math.round(Math.pow(1024, base - Math.floor(base))) + ' ' + suffixes[Math.floor(base)]
|
|
}
|
|
|
|
}
|
|
|
|
export default File |