I wrote a NodeJS HTTP server specifically for serving static files. I didn't bother much about security since the server is going to be used locally in my Electron application.
function buildStaticServer() {
const fs = require("fs");
const urlModule = require("url");
return require("http").createServer(function(req, res) {
var parsedUrl = urlModule.parse(req.url, true);
var completePath = __dirname + parsedUrl.pathname;
console.log(completePath);
fs.stat(completePath, function(err, statObj){
//we first check if the pathName exists
if(err){
res.writeHead(404);
return res.end("404 Directory not found");
}
if(statObj.isDirectory()){
//if the pathname is a directory, we're gonna try to send the index.html in that directory
fs.readFile(completePath + "/index.html", function(err, data){
if(err){
res.writeHead(404);
return res.end("404 File Corrupt or Not Found");
}
res.writeHead(200);
res.write(data);
return res.end();
})
}
fs.readFile(completePath, function(err, data){
if(err){
res.writeHead(404);
res.end("404 File Corrupt or Not Found");
return;
}
res.writeHead(200);
res.write(data);
return res.end();
})
});
});
}
var staticServer = buildStaticServer().listen(9000);