Skip to content

Instantly share code, notes, and snippets.

@nilsandrey
Last active May 2, 2024 02:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nilsandrey/168ffcb4e6ded862c94ee61dc8f1805e to your computer and use it in GitHub Desktop.
Save nilsandrey/168ffcb4e6ded862c94ee61dc8f1805e to your computer and use it in GitHub Desktop.
NodeJS based directory browsing and file serve without dependencies
// NodeJS based directory browsing and file serve without dependencies
// Joining code from <https://stackoverflow.com/questions/16333790/node-js-quick-file-server-static-files-over-http>
var fs = require("fs"),
http = require("http");
http
.createServer(function (req, res) {
// Website you wish to allow to connect
res.setHeader("Access-Control-Allow-Origin", "*");
// Request methods you wish to allow
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
// Request headers you wish to allow
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);
const requestItem = __dirname + req.url;
const stats = fs.statSync(requestItem);
if (stats.isDirectory()) {
//Get list of files and folder in requested directory
const lsof = fs.readdirSync(requestItem, {
encoding: "utf8",
withFileTypes: false,
});
// make an html page with the list of files and send to browser
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(html_page(req.url, lsof));
// return;
} else
fs.readFile(requestItem, function (err, data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
})
.listen(8086);
function html_page(req_url, lsof) {
//this is a Function declarations can be called before it is defined
// Add link to root directory and parent directory if not already in root directory
const list = req_url == "/" ? [] : [`<a href=/>/</a>`, `<a href=../>..</a>`];
const template = (file) => {
// the above is a Function expressions cannot be called before it is defined
return `<a href=${encodeURI(req_url)}${
req_url.slice(-1) == "/" ? "" : "/"
}${encodeURI(file)}>${file}</a>`;
};
// Add all the links to the files and folder in requested directory
lsof.forEach((file) => {
list.push(template(file));
});
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html" charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Directory of ${req_url}</title>
</head>
<body>
<h2>Directory of ${req_url}</h2>
${list.join("<br/>\n")}
</body>
</html>`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment