local-server
Advanced tools
Comparing version
@@ -7,15 +7,10 @@ #!/usr/bin/env node | ||
, mime = require('mime') | ||
, mnm = require('minimist') | ||
var port = 8000 | ||
, root = process.cwd() | ||
var argv = mnm(process.argv.slice(2)) | ||
, port = argv.p || 8000 | ||
, root = argv.r || process.cwd() | ||
, fallbackPath = argv.f | ||
if (process.argv.length > 2) { | ||
if (isNaN(process.argv[2])) { | ||
root = process.argv[2] || root | ||
port = +process.argv[3] || port | ||
} else { | ||
port = +process.argv[2] || port | ||
root = process.argv[3] || root | ||
} | ||
} | ||
if (fallbackPath) fallbackPath = path.join(root, fallbackPath) | ||
@@ -29,11 +24,19 @@ http.createServer(function requestHandler(req, res) { | ||
function handle(filePath) { | ||
function handle(filePath, fallingback) { | ||
fs.stat(filePath, function(err, stat) { | ||
if (err) { | ||
res.statusCode = err.code == 'ENOENT' ? 404 : 500 | ||
if (err.code == 'ENOENT') { | ||
if (!fallingback && fallbackPath) return handle(fallbackPath, true) | ||
res.statusCode = 404 | ||
} | ||
else res.statusCode = 500 | ||
res.end() | ||
console.error(err) | ||
} else if (stat.isDirectory()) { | ||
} | ||
else if (stat.isDirectory()) { | ||
handle(path.join(filePath, 'index.html')) | ||
} else { | ||
} | ||
else { | ||
var contentType = mime.lookup(path.extname(filePath)) | ||
@@ -47,2 +50,2 @@ res.writeHead(200, { 'Content-Type': contentType }) | ||
console.log('Server running at http://localhost:' + port + '/' + ' [root: ' + root + ']') | ||
console.log('Server running at http://localhost:' + port + '/' + ' [root: ' + root + ', fallback: ' + fallbackPath + ']') |
{ | ||
"name": "local-server", | ||
"version": "0.1.5", | ||
"version": "0.1.6", | ||
"description": "Static web server", | ||
@@ -19,3 +19,4 @@ "homepage": "http://buunguyen.github.io/local-server", | ||
"dependencies": { | ||
"mime": "~1.2.11" | ||
"mime": "~1.2.11", | ||
"minimist": "^0.2.0" | ||
}, | ||
@@ -27,2 +28,2 @@ "license": "MIT", | ||
} | ||
} | ||
} |
@@ -14,12 +14,17 @@ local-server | ||
``` | ||
lserver [optional port] [optional root folder] | ||
lserver -p [port] -r [root folder] -f [fallback path if not found] | ||
``` | ||
Arguments (all are optional): | ||
* `p`: [`Number`] port number, default to 8000 | ||
* `r`: [`String`] root folder, default to working directory | ||
* `f`: [`String`] fallback path when page not found, default to not falling back and send 404 | ||
For example | ||
``` | ||
lserver 8080 ./ | ||
=> Server running at http://localhost:8000/ [root: ./] | ||
lserver -p 9000 -r ./ -f index.html | ||
=> Server running at http://localhost:9000/ [root: ./, fallback: index.html] | ||
``` | ||
Note: both port and root folder are optional and can be specified in any order | ||
That's all! |
3658
12%40
5.26%29
20.83%2
100%+ Added
+ Added