Skip to content

Commit

Permalink
feat: add --base-dir to cli options to specify base path (#837)
Browse files Browse the repository at this point in the history
* Add baseDir option, add --baseDir flag to cli options to specify base path

* add path to logged URLs

* Address feedback from @thornjad, add --base-dir flag

* base-dir tests

---------

Co-authored-by: Jesse Ditson <[email protected]>
Co-authored-by: Jesse Ditson <[email protected]>
Co-authored-by: max.sagan <[email protected]>
Co-authored-by: Eric Dubé <[email protected]>
  • Loading branch information
5 people authored Nov 5, 2024
1 parent 3b86caa commit fe91590
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 4 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ with the provided Dockerfile.
| ------------- |-------------|-------------|
|`-p` or `--port` |Port to use. Use `-p 0` to look for an open port, starting at 8080. It will also read from `process.env.PORT`. |8080 |
|`-a` |Address to use |0.0.0.0|
|`--base-dir` | Base path to serve files from | `/` |
|`-d` |Show directory listings |`true` |
|`-i` | Display autoIndex | `true` |
|`-g` or `--gzip` |When enabled it will serve `./public/some-file.js.gz` in place of `./public/some-file.js` when a gzipped version of the file exists and the request accepts gzip encoding. If brotli is also enabled, it will try to serve brotli first.|`false`|
Expand Down
14 changes: 10 additions & 4 deletions bin/http-server
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ if (argv.h || argv.help) {
' -p --port Port to use. If 0, look for open port. [8080]',
' -a Address to use [0.0.0.0] or [::]',
' -d Show directory listings [true]',
' --base-dir Base directory to serve files from [/]',
' -i Display autoIndex [true]',
' -g --gzip Serve gzip files when possible [false]',
' -b --brotli Serve brotli files when possible [false]',
Expand Down Expand Up @@ -77,6 +78,7 @@ var port = argv.p || argv.port || parseInt(process.env.PORT, 10),
proxyOptions = argv['proxy-options'],
utc = argv.U || argv.utc,
version = argv.v || argv.version,
baseDir = argv['base-dir'],
logger;

var proxyOptionsBooleanProps = [
Expand Down Expand Up @@ -146,6 +148,7 @@ function listen(port) {
cache: argv.c,
timeout: argv.t,
showDir: argv.d,
baseDir: baseDir,
autoIndex: argv.i,
gzip: argv.g || argv.gzip,
brotli: argv.b || argv.brotli,
Expand Down Expand Up @@ -220,7 +223,8 @@ function listen(port) {

var server = httpServer.createServer(options);
server.listen(port, host, function () {
var protocol = tls ? 'https://' : 'http://';
var protocol = tls ? 'https://' : 'http://',
path = baseDir ? '/' + baseDir.replace(/^\//, '') : '';

logger.info([
chalk.yellow('Starting up http-server, serving '),
Expand All @@ -239,7 +243,8 @@ function listen(port) {
([chalk.yellow('AutoIndex: '), argv.i ? chalk.red('not visible') : chalk.cyan('visible')].join('')),
([chalk.yellow('Serve GZIP Files: '), argv.g || argv.gzip ? chalk.cyan('true') : chalk.red('false')].join('')),
([chalk.yellow('Serve Brotli Files: '), argv.b || argv.brotli ? chalk.cyan('true') : chalk.red('false')].join('')),
([chalk.yellow('Default File Extension: '), argv.e ? chalk.cyan(argv.e) : (argv.ext ? chalk.cyan(argv.ext) : chalk.red('none'))].join(''))
([chalk.yellow('Default File Extension: '), argv.e ? chalk.cyan(argv.e) : (argv.ext ? chalk.cyan(argv.ext) : chalk.red('none'))].join('')),
([chalk.yellow('Base directory: '), baseDir ? chalk.cyan(baseDir) : chalk.cyan('/')].join(''))
].join('\n'));

if (options.headers) {
Expand All @@ -252,13 +257,14 @@ function listen(port) {

logger.info(chalk.yellow('\nAvailable on:'));


if (argv.a && (host !== '::' || host !== '0.0.0.0')) {
logger.info(` ${protocol}${host}:${chalk.green(port.toString())}`);
logger.info(` ${protocol}${host}:${chalk.green(port.toString())}${path}`);
} else {
Object.keys(ifaces).forEach(function (dev) {
ifaces[dev].forEach(function (details) {
if (details.family === 'IPv4') {
logger.info((' ' + protocol + details.address + ':' + chalk.green(port.toString())));
logger.info((' ' + protocol + details.address + ':' + chalk.green(port.toString()) + path));
}
if (details.family === 'IPv6' && !details.address.startsWith("fe80") ) { // Ignoring Ipv6-Link Local addresses
logger.info((' ' + protocol + details.address + ':' + chalk.green(port.toString())));
Expand Down
1 change: 1 addition & 0 deletions lib/http-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ function HttpServer(options) {

before.push(httpServerCore({
root: this.root,
baseDir: options.baseDir,
cache: this.cache,
showDir: this.showDir,
showDotfiles: this.showDotfiles,
Expand Down
31 changes: 31 additions & 0 deletions test/main.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,37 @@ test('http-server main', (t) => {
}
});
}),

new Promise((resolve) => {
const server = httpServer.createServer({
root,
baseDir: '/test'
});

server.listen(8084, async () => {
try {
await Promise.all([
// should serve files at the specified baseDir
requestAsync("http://localhost:8084/test/file").then(async (res) => {
t.equal(res.statusCode, 200);
const fileData = await fsReadFile(path.join(root, 'file'), 'utf8');
t.equal(res.body.trim(), fileData.trim());
}).catch(err => t.fail(err.toString())),

// should not serve files at the root
requestAsync("http://localhost:8084/file").then((res) => {
t.equal(res.statusCode, 403);
t.equal(res.body, '');
}).catch(err => t.fail(err.toString())),
]);
} catch (err) {
t.fail(err.toString());
} finally {
server.close();
resolve();
}
});
}),
]).then(() => t.end())
.catch(err => {
t.fail(err.toString());
Expand Down

0 comments on commit fe91590

Please sign in to comment.