Last active
November 27, 2019 06:45
-
-
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
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 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternatively, we can install http-server with
npm i http-server -g
andrun 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 withserviceWorker
though. which again seems to work withhttp-server