Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,18 @@ Using `npx` you can run the script without installing it first:

`-v` or `--version` Print the version and exit.

### Configuration file

In addition to command line options, `http-server` will look for options in an `.httpserverrc` file:

{
"p": "8888",
"a": "localhost",
"silent": true
}

The search for `.httpserverrc` starts in the directory to be served, traversing up the directory tree until one is found.

## Magic Files

- `index.html` will be served as the default file to any directory requests.
Expand Down
232 changes: 161 additions & 71 deletions bin/http-server
Original file line number Diff line number Diff line change
Expand Up @@ -8,74 +8,163 @@ var colors = require('colors/safe'),
portfinder = require('portfinder'),
opener = require('opener'),
fs = require('fs'),
argv = require('optimist')
.boolean('cors')
.boolean('log-ip')
.argv,
nconf = require('nconf'),
path = require('path'),
pjson = require('../package.json');

var ifaces = os.networkInterfaces();
var config = nconf.argv({
p: {
alias: 'port',
describe: 'Port to use. By default, searches for an open port starting from 8080.',
number: true
},
a: {
default: '0.0.0.0',
describe: 'Address to use'
},
d: {
boolean: true,
default: true,
describe: 'Show directory listings'
},
i: {
boolean: true,
default: true,
describe: 'Display autoIndex'
},
g: {
alias: 'gzip',
boolean: true,
default: false,
describe: 'Serve gzip files when possible'
},
b: {
alias: 'brotli',
boolean: true,
default: false,
describe: 'Serve brotli files when possible. If both brotli and gzip are enabled, brotli takes precedence.'
},
e: {
alias: 'ext',
describe: 'Default file extension if none supplied'
},
s: {
alias: 'silent',
boolean: true,
describe: 'Suppress log messages from output'
},
cors: {
describe: 'Enable CORS via the "Access-Control-Allow-Origin" header. Optionally provide CORS headers list separated by commas.'
},
o: {
describe: 'Open browser window after starting the server. Optionally provide a URL path to open the browser window to.'
},
c: {
default: 3600,
describe: 'Cache time (max-age) in seconds, e.g. -c10 for 10 seconds. To disable caching, use -c-1.',
number: true
},
t: {
describe: 'Connections timeout in seconds [120], e.g. -t60 for 1 minute. To disable timeout, use -t0',
number: true
},
U: {
alias: 'utc',
boolean: true,
describe: 'Use UTC time format in log messages.'
},
'log-ip': {
boolean: true,
describe: 'Enable logging of the client\'s IP address'
},
P: {
alias: 'proxy',
describe: 'Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com'
},
username: {
describe: 'Username for basic authentication. Can also be specified with the env variable NODE_HTTP_SERVER_USERNAME.'
},
password: {
describe: 'Password for basic authentication. Can also be specified with the env variable NODE_HTTP_SERVER_PASSWORD'
},
S: {
alias: 'ssl',
boolean: true,
describe: 'Enable https.'
},
C: {
alias: 'cert',
default: 'cert.pem',
describe: 'Path to ssl cert file.'
},
K: {
alias: 'key',
default: 'key.pem',
describe: 'Path to ssl key file.'
},
r: {
alias: 'robots',
default: 'User-agent: *\\nDisallow: /',
describe: 'Respond to /robots.txt'
},
'no-dotfiles': {
boolean: true,
describe: 'Do not show dotfiles'
},
h: {
alias: 'help',
describe: 'Print this list and exit.'
},
v: {
alias: 'version',
describe: 'Print the version and exit.'
}
}),
ifaces = os.networkInterfaces();

process.title = 'http-server';

if (argv.h || argv.help) {
if (config.get('h')) {
console.log([
'usage: http-server [path] [options]',
'',
'options:',
' -p --port Port to use [8080]',
' -a Address to use [0.0.0.0]',
' -d Show directory listings [true]',
' -i Display autoIndex [true]',
' -g --gzip Serve gzip files when possible [false]',
' -b --brotli Serve brotli files when possible [false]',
' If both brotli and gzip are enabled, brotli takes precedence',
' -e --ext Default file extension if none supplied [none]',
' -s --silent Suppress log messages from output',
' --cors[=headers] Enable CORS via the "Access-Control-Allow-Origin" header',
' Optionally provide CORS headers list separated by commas',
' -o [path] Open browser window after starting the server.',
' Optionally provide a URL path to open the browser window to.',
' -c Cache time (max-age) in seconds [3600], e.g. -c10 for 10 seconds.',
' To disable caching, use -c-1.',
' -t Connections timeout in seconds [120], e.g. -t60 for 1 minute.',
' To disable timeout, use -t0',
' -U --utc Use UTC time format in log messages.',
' --log-ip Enable logging of the client\'s IP address',
'',
' -P --proxy Fallback proxy if the request cannot be resolved. e.g.: http://someurl.com',
'',
' --username Username for basic authentication [none]',
' Can also be specified with the env variable NODE_HTTP_SERVER_USERNAME',
' --password Password for basic authentication [none]',
' Can also be specified with the env variable NODE_HTTP_SERVER_PASSWORD',
'',
' -S --ssl Enable https.',
' -C --cert Path to ssl cert file (default: cert.pem).',
' -K --key Path to ssl key file (default: key.pem).',
'',
' -r --robots Respond to /robots.txt [User-agent: *\\nDisallow: /]',
' --no-dotfiles Do not show dotfiles',
' -h --help Print this list and exit.',
' -v --version Print the version and exit.'
config.stores.argv.help()
].join('\n'));
process.exit();
}

var port = argv.p || argv.port || parseInt(process.env.PORT, 10),
host = argv.a || '0.0.0.0',
ssl = argv.S || argv.ssl,
proxy = argv.P || argv.proxy,
utc = argv.U || argv.utc,
var root = config.get('_')[0];

if (!root) {
try {
fs.lstatSync('./public');
root = './public';
}
catch (err) {
root = './';
}
}

config.file({
file: '.httpserverrc',
dir: path.resolve(root),
search: true
});

var port = config.get('p') || parseInt(process.env.PORT, 10),
host = config.get('a'),
ssl = config.get('S'),
proxy = config.get('P'),
utc = config.get('U'),
logger,
version = pjson.version;

if (!argv.s && !argv.silent) {
if (!config.get('s')) {
logger = {
info: console.log,
request: function (req, res, error) {
var date = utc ? new Date().toUTCString() : new Date();
var ip = argv['log-ip']
var ip = config.get('log-ip')
? req.headers['x-forwarded-for'] || '' + req.connection.remoteAddress
: '';
if (error) {
Expand Down Expand Up @@ -113,40 +202,40 @@ else {
listen(port);
}

if (argv.v || argv.version) {
if (config.get('v')) {
console.log(version);
process.exit();
}

function listen(port) {
var options = {
root: argv._[0],
cache: argv.c,
timeout: argv.t,
showDir: argv.d,
autoIndex: argv.i,
gzip: argv.g || argv.gzip,
brotli: argv.b || argv.brotli,
robots: argv.r || argv.robots,
ext: argv.e || argv.ext,
root: config.get('_')[0],
cache: config.get('c'),
timeout: config.get('t'),
showDir: config.get('d'),
autoIndex: config.get('i'),
gzip: config.get('g'),
brotli: config.get('b'),
robots: config.get('r'),
ext: config.get('e'),
logFn: logger.request,
proxy: proxy,
showDotfiles: argv.dotfiles,
username: argv.username || process.env.NODE_HTTP_SERVER_USERNAME,
password: argv.password || process.env.NODE_HTTP_SERVER_PASSWORD
showDotfiles: config.get('dotfiles'),
username: config.get('username') || process.env.NODE_HTTP_SERVER_USERNAME,
password: config.get('password') || process.env.NODE_HTTP_SERVER_PASSWORD
};

if (argv.cors) {
if (config.get('cors')) {
options.cors = true;
if (typeof argv.cors === 'string') {
options.corsHeaders = argv.cors;
if (typeof config.get('cors') === 'string') {
options.corsHeaders = config.get('cors');
}
}

if (ssl) {
options.https = {
cert: argv.C || argv.cert || 'cert.pem',
key: argv.K || argv.key || 'key.pem'
cert: config.get('C'),
key: config.get('K')
};
try {
fs.lstatSync(options.https.cert);
Expand Down Expand Up @@ -175,7 +264,7 @@ function listen(port) {
colors.yellow('\nAvailable on:')
].join(''));

if (argv.a && host !== '0.0.0.0') {
if (config.get('a') && host !== '0.0.0.0') {
logger.info((' ' + protocol + canonicalHost + ':' + colors.green(port.toString())));
}
else {
Expand All @@ -193,10 +282,11 @@ function listen(port) {
}

logger.info('Hit CTRL-C to stop the server');
if (argv.o) {
var o = config.get('o');
if (o) {
var openUrl = protocol + canonicalHost + ':' + port;
if (typeof argv.o === 'string') {
openUrl += argv.o[0] === '/' ? argv.o : '/' + argv.o;
if (typeof o === 'string') {
openUrl += o[0] === '/' ? o : '/' + o;
}
logger.info('open: ' + openUrl);
opener(openUrl);
Expand Down
Loading