FileSharer/index.js
2024-01-16 18:27:26 +00:00

47 lines
No EOL
1.2 KiB
JavaScript

const express = require("express"),
fs = require("fs"),
path = require("path")
var app = express()
var PORT = process.env.PORT || 8080
var directory = process.env.FILES_DIR
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)
app.use(express.static(directory))
if (!directory) {
console.error("No directory specified! Please specify one using the environment variable FILES_DIR.")
return
}
app.listen(PORT, () => {
console.log("Now listening on PORT: " + PORT)
})
app.get("/*", (req, res) => {
var file = req.params[0]
var absPath = path.join(directory, file)
try {
var dirContents = fs.readdirSync(absPath)
} catch (error) {
res.send("<p>404: not found!</p>")
}
res.write(baseStart)
res.write('<a href="../">Parent Directory</a><br>')
for (let index = 0; index < dirContents.length; index++) {
const file = dirContents[index];
res.write(`<a href="./${file}">${file}</a><br>`)
}
res.write(baseEnd)
res.end()
})