Skip to content

Instantly share code, notes, and snippets.

@jsuryahyd
Last active November 27, 2019 06:45
Show Gist options
  • Save jsuryahyd/ae550b85b16154b7db365df4ae194057 to your computer and use it in GitHub Desktop.
Save jsuryahyd/ae550b85b16154b7db365df4ae194057 to your computer and use it in GitHub Desktop.
node server for serving static files when using angular or react built in production mode
const http = require("http");
const fs = require("fs");
const pathToStaticFilesFolder = "./dist";//or whererver
http
.createServer((req, res) => {
console.log(req.url);
let fileStream;
//if no path or path doesnot contain a file extension
if (req.url == "/" || req.url.split(".").length == 1) {
res.writeHead(200, { "Content-Type": "text/html" });
fileStream = fs.createReadStream(`${pathToStaticFilesFolder}/index.html`);
} else {
let contentType = "text/plain";
switch (req.url.split(".").reverse()[0]) {
//donot set content type
case "svg":
//svg gets xml content type, which browsers will not take as image,so.
contentType = "image/svg+xml";
break;
case "js":
contentType = "application/javascript";
break;
case "css":
contentType = "text/css";
break;
case "json":
contentType = "application/json";
break;
case "webmanifest": //PWA
contentType = "application/manifest+json";
break;
default:
contentType = "text/plain";
}
res.writeHead(200, { "Content-Type": contentType });
fileStream = fs.createReadStream(pathToStaticFilesFolder + req.url);
}
fileStream.on("error", (...args) => {
console.error("------------ file read error -----------\n", args);
res.end();
});
fileStream.pipe(res);
})
.listen(2019);
@jsuryahyd
Copy link
Author

jsuryahyd commented Sep 6, 2019

Alternatively, we can install http-server with npm i http-server -g and
run in terminal
npx http-server {folder_path}
But then all the routes other than root path will only be served if accessed as localhost, we cannot access other paths with ip address. While this script, just works there too. There is a problem with serviceWorker though. which again seems to work with http-server

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment