From 6971adf5799a11fcc8d78de98733cd104df05773 Mon Sep 17 00:00:00 2001 From: Violet <110205356+Violets-puragtory@users.noreply.github.com> Date: Fri, 2 Feb 2024 20:13:13 +0000 Subject: [PATCH] Show file sizes --- index.js | 39 +++++++++++++++++++++++++++++++-------- resources/base.html | 4 +++- 2 files changed, 34 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index 4099012..54e2586 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,6 @@ const express = require("express"), -fs = require("fs"), -path = require("path") + fs = require("fs"), + path = require("path") var app = express() @@ -8,6 +8,28 @@ var PORT = process.env.PORT || 8080 var directory = process.env.FILES_DIR +function humanFileSize(bytes, si = false, dp = 1) { + const thresh = si ? 1000 : 1024; + + if (Math.abs(bytes) < thresh) { + return bytes + ' B'; + } + + const units = si + ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] + : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']; + let u = -1; + const r = 10 ** dp; + + do { + bytes /= thresh; + ++u; + } while (Math.round(Math.abs(bytes) * r) / r >= thresh && u < units.length - 1); + + + return bytes.toFixed(dp) + ' ' + units[u]; +} + var baseHTML = fs.readFileSync(path.join(__dirname, 'resources/base.html')).toString() var baseStart = baseHTML.substring(0, baseHTML.indexOf('{CONTENT}')) var baseEnd = baseHTML.substring(baseHTML.indexOf('{CONTENT}') + 9, baseHTML.length) @@ -26,7 +48,7 @@ app.listen(PORT, () => { app.get("/*", (req, res) => { var file = req.params[0] var absPath = path.join(directory, file) - + res.setHeader('Content-Type', 'text/html') res.setHeader("X-Accel-Buffering", "no") @@ -49,9 +71,8 @@ app.get("/*", (req, res) => { for (let index = 0; index < dirContents.length; index++) { const file = dirContents[index]; var fileStats = fs.statSync(path.join(absPath, file)) - // console.log(fileStats.isDirectory) if (!fileStats.isDirectory()) { - res.write(`${file}
`) + res.write(`
  • ${file} | ${humanFileSize(fileStats.size)}
  • `) } else { dirs.push(file) } @@ -60,9 +81,11 @@ app.get("/*", (req, res) => { for (let index = 0; index < dirs.length; index++) { const file = dirs[index]; - res.write(`./${file}/
    `) - - } + var fileStats = fs.statSync(path.join(absPath, file)) + + res.write(`
  • ./${file}/
  • `) + + } // res.write(`./${file}/
    `) res.write(baseEnd) diff --git a/resources/base.html b/resources/base.html index a6381ac..527b564 100644 --- a/resources/base.html +++ b/resources/base.html @@ -10,6 +10,8 @@ {TITLE} - {CONTENT} + \ No newline at end of file