Last active
October 1, 2019 08:46
-
-
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.
This file contains hidden or 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
{ | |
"name": "dev-http-server", | |
"version": "0.0.1", | |
"description": "Development HTTP server serving the current duirectory.", | |
"license": "MIT", | |
"author": "Ferdinand Prantl <[email protected]> (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" | |
] | |
} |
This file contains hidden or 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
// 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