Skip to content

Instantly share code, notes, and snippets.

@prantlf
Last active October 1, 2019 08:46
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 prantlf/2514e4b43b8c6ef6ab08a4d2084a69ba to your computer and use it in GitHub Desktop.
Save prantlf/2514e4b43b8c6ef6ab08a4d2084a69ba to your computer and use it in GitHub Desktop.
Serves files from the current directory and subdirectories over HTTP for local development purposes using multiple workers.
{
"name": "dev-http-server",
"version": "0.0.1",
"description": "Development HTTP server serving the current duirectory.",
"license": "MIT",
"author": "Ferdinand Prantl <prantlf@gmail.com> (http://prantl.tk/)",
"contributors": [],
"homepage": "https://gist.github.com/prantlf/2514e4b43b8c6ef6ab08a4d2084a69ba",
"repository": "https://gist.github.com/prantlf/2514e4b43b8c6ef6ab08a4d2084a69ba",
"bugs": "https://gist.github.com/prantlf/2514e4b43b8c6ef6ab08a4d2084a69ba",
"engines": {
"node": ">=8"
},
"dependencies": {
"cluster": "0.7.7",
"compression": "1.7.4",
"connect": "3.7.0",
"serve-index": "1.9.1",
"serve-static": "1.14.1"
},
"keywords": [
"http-server",
"web-server",
"server",
"http",
"development"
]
}
// Serves files from the current directory and subdirectories over HTTP.
const { HOST, PORT, WORKER_COUNT } = process.env
const host = HOST || '0.0.0.0'
const port = PORT || 9001
const workerCount = parseInt(WORKER_COUNT || 2)
const cluster = require('cluster')
if (cluster.isMaster) {
console.log(`Master ${process.pid} is starting ${workerCount} workers...`)
for (let i = 0; i < workerCount; ++i) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) =>
console.log(`Worker ${worker.process.pid} has exited with the code ${code}.`))
return
}
const http = require('http')
const connect = require('connect')
const compression = require('compression')
const serveStatic = require('serve-static')
const serveIndex = require('serve-index')
const handler = connect()
.use(compression())
.use(serveStatic('.', { etag: false }))
.use(serveIndex('.'))
http
.createServer(handler)
.listen(port, host, error => {
if (error) {
console.error(error);
} else {
console.log(`Worker ${process.pid} is listening at http://${host}:${port}...`);
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment