Created
March 25, 2022 23:35
-
-
Save lex-world/5475317e74629469451051c0de4f01a2 to your computer and use it in GitHub Desktop.
File Server in Node.js without DB installation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cluster = require("cluster"); | |
// deepcode ignore HttpToHttps: https provided on production with NGINX | |
const http = require("http"); | |
const numCPUs = require("os").cpus().length; | |
const process = require("process"); | |
const statik = require("node-static"); | |
/** | |
* @dev folder listener | |
*/ | |
const public = new statik.Server("./public"); | |
if (cluster.isPrimary) { | |
console.log(`Primary ${process.pid} is running`); | |
for (let i = 0; i < numCPUs; i++) cluster.fork(); | |
cluster.on("exit", (worker) => | |
console.log(`worker ${worker.process.pid} died`) | |
); | |
} else { | |
http | |
.createServer((req, res) => | |
req | |
.addListener("end", () => { | |
public.serve(req, res, (err) => { | |
if (err) { | |
console.error("Error serving\t" + req.url + " - " + err.message); | |
res.writeHead(err.status, err.headers).end(); | |
} | |
}); | |
}) | |
.resume() | |
) | |
.listen(process.env.PORT || 8000); | |
console.log(`Worker ${process.pid} started`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment