-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
http-server
executable file
·264 lines (239 loc) · 8.92 KB
/
http-server
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env node
'use strict';
var colors = require('colors/safe'),
os = require('os'),
httpServer = require('../lib/http-server'),
portfinder = require('portfinder'),
opener = require('opener'),
fs = require('fs');
var argv = require('minimist')(process.argv.slice(2), {
alias: {
tls: 'ssl'
}
});
var ifaces = os.networkInterfaces();
process.title = 'http-server';
if (argv.h || argv.help) {
console.log([
'usage: http-server [path] [options]',
'',
'options:',
' -p --port Port to use. If 0, look for open port. [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',
' --proxy-options Pass options to proxy using nested dotted objects. e.g.: --proxy-options.secure false',
'',
' --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 --tls --ssl Enable secure request serving with TLS/SSL (HTTPS)',
' -C --cert Path to TLS cert file (default: cert.pem)',
' -K --key Path to TLS key file (default: key.pem)',
'',
' -r --robots Respond to /robots.txt [User-agent: *\\nDisallow: /]',
' --no-dotfiles Do not show dotfiles',
' --mimetypes Path to a .types file for custom mimetype definition',
' -h --help Print this list and exit.',
' -v --version Print the version and exit.'
].join('\n'));
process.exit();
}
var port = argv.p || argv.port || parseInt(process.env.PORT, 10),
host = argv.a || '0.0.0.0',
tls = argv.S || argv.tls,
proxy = argv.P || argv.proxy,
proxyOptions = argv['proxy-options'],
utc = argv.U || argv.utc,
version = argv.v || argv.version,
logger;
var proxyOptionsBooleanProps = [
'ws', 'xfwd', 'secure', 'toProxy', 'prependPath', 'ignorePath', 'changeOrigin',
'preserveHeaderKeyCase', 'followRedirects', 'selfHandleResponse'
];
if (proxyOptions) {
Object.keys(proxyOptions).forEach(function (key) {
if (proxyOptionsBooleanProps.indexOf(key) > -1) {
proxyOptions[key] = proxyOptions[key].toLowerCase() === 'true';
}
});
}
if (!argv.s && !argv.silent) {
logger = {
info: console.log,
request: function (req, res, error) {
var date = utc ? new Date().toUTCString() : new Date();
var ip = argv['log-ip']
? req.headers['x-forwarded-for'] || '' + req.connection.remoteAddress
: '';
if (error) {
logger.info(
'[%s] %s "%s %s" Error (%s): "%s"',
date, ip, colors.red(req.method), colors.red(req.url),
colors.red(error.status.toString()), colors.red(error.message)
);
}
else {
logger.info(
'[%s] %s "%s %s" "%s"',
date, ip, colors.cyan(req.method), colors.cyan(req.url),
req.headers['user-agent']
);
}
}
};
}
else if (colors) {
logger = {
info: function () {},
request: function () {}
};
}
if (version) {
logger.info('v' + require('../package.json').version);
process.exit();
}
if (!port) {
portfinder.basePort = 8080;
portfinder.getPort(function (err, port) {
if (err) { throw err; }
listen(port);
});
}
else {
listen(port);
}
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,
logFn: logger.request,
proxy: proxy,
proxyOptions: proxyOptions,
showDotfiles: argv.dotfiles,
mimetypes: argv.mimetypes,
username: argv.username || process.env.NODE_HTTP_SERVER_USERNAME,
password: argv.password || process.env.NODE_HTTP_SERVER_PASSWORD
};
if (argv.cors) {
options.cors = true;
if (typeof argv.cors === 'string') {
options.corsHeaders = argv.cors;
}
}
if (tls) {
options.https = {
cert: argv.C || argv.cert || 'cert.pem',
key: argv.K || argv.key || 'key.pem'
};
try {
fs.lstatSync(options.https.cert);
}
catch (err) {
logger.info(colors.red('Error: Could not find certificate ' + options.https.cert));
process.exit(1);
}
try {
fs.lstatSync(options.https.key);
}
catch (err) {
logger.info(colors.red('Error: Could not find private key ' + options.https.key));
process.exit(1);
}
}
var server = httpServer.createServer(options);
server.listen(port, host, function () {
var protocol = tls ? 'https://' : 'http://';
logger.info([
colors.yellow('Starting up http-server, serving '),
colors.cyan(server.root),
tls ? (colors.yellow(' through') + colors.cyan(' https')) : ''
].join(''));
logger.info([colors.yellow('\nhttp-server version: '), colors.cyan(require('../package.json').version)].join(''));
logger.info([
colors.yellow('\nhttp-server settings: '),
([colors.yellow('CORS: '), argv.cors ? colors.cyan(argv.cors) : colors.red('disabled')].join('')),
([colors.yellow('Cache: '), argv.c ? (argv.c === '-1' ? colors.red('disabled') : colors.cyan(argv.c + ' seconds')) : colors.cyan('3600 seconds')].join('')),
([colors.yellow('Connection Timeout: '), argv.t === '0' ? colors.red('disabled') : (argv.t ? colors.cyan(argv.t + ' seconds') : colors.cyan('120 seconds'))].join('')),
([colors.yellow('Directory Listings: '), argv.d ? colors.red('not visible') : colors.cyan('visible')].join('')),
([colors.yellow('AutoIndex: '), argv.i ? colors.red('not visible') : colors.cyan('visible')].join('')),
([colors.yellow('Serve GZIP Files: '), argv.g || argv.gzip ? colors.cyan('true') : colors.red('false')].join('')),
([colors.yellow('Serve Brotli Files: '), argv.b || argv.brotli ? colors.cyan('true') : colors.red('false')].join('')),
([colors.yellow('Default File Extension: '), argv.e ? colors.cyan(argv.e) : (argv.ext ? colors.cyan(argv.ext) : colors.red('none'))].join(''))
].join('\n'));
logger.info(colors.yellow('\nAvailable on:'));
if (argv.a && host !== '0.0.0.0') {
logger.info(` ${protocol}${host}:${colors.green(port.toString())}`);
} else {
Object.keys(ifaces).forEach(function (dev) {
ifaces[dev].forEach(function (details) {
if (details.family === 'IPv4') {
logger.info((' ' + protocol + details.address + ':' + colors.green(port.toString())));
}
});
});
}
if (typeof proxy === 'string') {
if (proxyOptions) {
logger.info('Unhandled requests will be served from: ' + proxy + '. Options: ' + JSON.stringify(proxyOptions));
}
else {
logger.info('Unhandled requests will be served from: ' + proxy);
}
}
logger.info('Hit CTRL-C to stop the server');
if (argv.o) {
const openHost = host === '0.0.0.0' ? '127.0.0.1' : host;
let openUrl = `${protocol}${openHost}:${port}`;
if (typeof argv.o === 'string') {
openUrl += argv.o[0] === '/' ? argv.o : '/' + argv.o;
}
logger.info('Open: ' + openUrl);
opener(openUrl);
}
// Spacing before logs
if (!argv.s) logger.info();
});
}
if (process.platform === 'win32') {
require('readline').createInterface({
input: process.stdin,
output: process.stdout
}).on('SIGINT', function () {
process.emit('SIGINT');
});
}
process.on('SIGINT', function () {
logger.info(colors.red('http-server stopped.'));
process.exit();
});
process.on('SIGTERM', function () {
logger.info(colors.red('http-server stopped.'));
process.exit();
});