Release 1.7 (#4094)
* Minor fixes in the Deployment doc Signed-off-by: Michail Kargakis <mkargaki@redhat.com> * add NodeRestriction to admission-controllers (#3842) * Admins Can Configure Zones in Storage Class The PR #38505 (https://github.com/kubernetes/kubernetes/pull/38505) added zones optional parameter to Storage Class for AWS and GCE provisioners. That's why documentation needs to be updated accordingly. * document custom resource definitions * add host paths to psp (#3971) * add host paths to psp * add italics * Update ConfigMap doc to explain TTL-based cache updates (#3989) * Update ConfigMap doc to explain TTL-based cache updates * swap word order Change "When a ConfigMap being already consumed..." to "When a ConfigMap already being consumed..." * Update NetworkPolicy docs for v1 * StorageOS Volume plugin * Update GPU docs * docs: HPA autoscaling/v2alpha1 status conditions This commit documents the new status conditions feature for HPA autoscaling/v2alpha1. It demonstrates how to get the status conditions using `kubectl describe`, and how to interpret them. * Update description about NodeRestriction kubelet node can alse create mirror pods for their own static pods. * adding storage as a supported resource to node allocatable Signed-off-by: Vishnu kannan <vishnuk@google.com> * Add documentation for podpreset opt-out annotation This adds the annotation for having the podpreset admission controller to skip (opt-out) manipulating the pod spec. Also, the annotation format for what presets have acted on a pod has been modified to add a prefix of "podpreset-". The new naming makes it such that there is no chance of collision with the newly introduced opt-out annotation (or future ones yet to be added). Opt-out annotation PR: kubernetes/kubernetes#44965 * Update PDB documentation to explain new field (#3885) * update-docs-pdb * Addressed erictune@'s comments * Fix title and add a TOC to the logging concept page * Patch #4118 for typos * Describe setting coredns server in nameserver resolv chain * Address comments in PR #3997. Comment is in https://github.com/kubernetes/kubernetes.github.io/pull/3997/files/f6eb59c67e28efc298c87b1ef49a96bc6adacd1e#diff-7a14981f3dd8eb203f897ce6c11d9828 * Update task for DaemonSet history and rollback (#4098) * Update task for DaemonSet history and rollback Also remove mentions of templateGeneration field because it's deprecated * Address comments * removed lt and gt as operators (#4152) * removed lt and gt as operators * replace lt and gt for node-affinfity * updated based on bsalamat review * Initial draft of upgrade guide for kubeadm clusters. In-place upgrades are supported between 1.6 and 1.7 releases. Rollback instructions to come in a separate commit. Fixes https://github.com/kubernetes/kubeadm/issues/278 * Add local volume documentation (#4050) * Add local volume documentation * Add PV local volume example * Patch PR #3999 * Add documentation for Stackdriver event exporter * Add documentation about controller metrics * Federation: Add task for setting up placement policies (#4075) * Add task for setting up placement policies * Update version of management sidecar in policy engine deployment * Address @nikhiljindal's comments - Lower case filenames - Comments in policy - Typo fixes - Removed type LoadBalancer from OPA Service * Add example that sets cluster selector Per-@nikhiljindal's suggestion * Fix wording and templating per @chenopis * PodDisruptionBudget documentation Improvements (#4140) * Changes from #3885 Title: Update PDB documentation to explain new field Author: foxish * Added Placeholder Disruptions Concept Guide New file: docs/concepts/workloads/pods/disruptions.md Intented contents: concept for Pod Disruption Budget, cross reference to Eviction and Preemption docs. Linked from: concepts > workloads > pods * Added placeholder Configuring PDB Task New file: docs/tasks/run-application/configure-pdb.md Intented contents: task for writing a Pod Disruption Budget. Linked from: tasks > configuring-applications > configure pdb. * Add refs to the "drain a node" task. * Refactor PDB docs. Move the "Requesting an eviction" section from: docs/tasks/administer-cluster/configure-pod-disruption-budget.md -- which is going away -- to: docs/tasks/administer-cluster/safely-drain-node.md The move is verbatim, except for an introductory sentence. Also added assignees. * Refactor of PDB docs Moved the section: Specifying a PodDisruptionBudget from: docs/tasks/administer-cluster/configure-pod-disruption-budget.md to: docs/tasks/run-application/configure-pdb.md because that former file is going away. Move is verbatim. * Explain how Eviction tools should handle failures * Refactor PDB docs Move text from: docs/tasks/administer-cluster/configure-pod-disruption-budget.md to: docs/concepts/workloads/pods/disruptions.md Delete the now empty: docs/tasks/administer-cluster/configure-pod-disruption-budget.md Added a redirects_from section to the new doc, containing the path of the now-deleted doc, plus all the redirects from the deleted doc. * Expand PDB Concept guide Building on a little content from the old task, greatly expanded the Disruptions concept guide, including an abstract example. * Update creating a pdb Task. * Address review comments. * Fixed for all cody-clark's review comments * Address review comments from mml * Address review comments from maisem * Fix missing backtick * Api and Kubectl reference docs updates for 1.7 (#4193) * Fix includes groups * Generated kubectl docs for 1.7 * Generated references docs for 1.7 api * Document node authorization mode * API Aggregator (#4173) * API Aggregator * Additional bullet points * incorporated feedback for apiserver-aggregation.md * split setup-api-aggregator.md into two docs and address feedback * fix link * addressed docs feedback * incorporate feedback * integrate feedback * Add documentation for DNS stub domains (#4063) * Add documentation for DNS stub domains * add additional prereq * fix image path * review feedback * minor grammar and style nits * documentation for using hostAliases to manage hosts file (#4080) * documentation for using hostAliases to manage hosts file * add to table of contents * review comments * update the right command to see hosts file * reformat doc based on suggestion and change some wording * Fix typo for #4080 * Patch PR #4063 * Fix wording in placement policy task introduction * Add update to statefulset concepts and basic tutorial (#4174) * Add update to statefulset concpets and basic tutorial * Address tech comments. * Update ESIPP docs for new added API fields * Custom resource docs * update audit document with advanced audit features added in 1.7 * kubeadm v1.7 documentation updates (#4018) * v1.7 updates for kubeadm * Address review comments * Address Luke's comments * Encrypting secrets at rest and cluster security guide * Edits for Custom DNS Documentation (#4207) * reorganize custom dns doc * format fixes * Update version numbers to 1.7 * Patch PR #4140 (#4215) * Patch PR #4140 * fix link and typos * Update PR template * Update TLS bootstrapping with 1.7 features This includes documenting the new CSR approver built into the controller manager and the kubelet alpha features for certificate rotation. Since the CSR approver changed over the 1.7 release cycle we need to call out the migration steps for those using the alpha feature. This document as a whole could probably use some updates, but the main focus of this PR is just to get these features minimally documented before the release. * Federated ClusterSelector formatting updates from review * complete PR #4181 (#4223) * complete PR #4181 * fix security link * Extensible admission controller (#4092) * extensible-admission-controllers * Update extensible-admission-controllers.md * more on initializers * fixes * Expand external admission webhooks documentation * wrap at 80 chars * more * add reference * Use correct apigroup for network policy * Docs changes to PR #4092 (#4224) * Docs changes to PR #4092 * address feedback * add doc for --as-group in cli Add doc for this pr: https://github.com/kubernetes/kubernetes/pull/43696
This commit is contained in:
+3
@@ -0,0 +1,3 @@
|
||||
npm-debug.log
|
||||
node_modules
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2010-14 Alexis Sellier
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
+234
@@ -0,0 +1,234 @@
|
||||
node-static
|
||||
===========
|
||||
|
||||
> a simple, *rfc 2616 compliant* file streaming module for [node](http://nodejs.org)
|
||||
|
||||
node-static understands and supports *conditional GET* and *HEAD* requests.
|
||||
node-static was inspired by some of the other static-file serving modules out there,
|
||||
such as node-paperboy and antinode.
|
||||
|
||||
Synopsis
|
||||
--------
|
||||
|
||||
```js
|
||||
var static = require('node-static');
|
||||
|
||||
//
|
||||
// Create a node-static server instance to serve the './public' folder
|
||||
//
|
||||
var file = new static.Server('./public');
|
||||
|
||||
require('http').createServer(function (request, response) {
|
||||
request.addListener('end', function () {
|
||||
//
|
||||
// Serve files!
|
||||
//
|
||||
file.serve(request, response);
|
||||
}).resume();
|
||||
}).listen(8080);
|
||||
```
|
||||
|
||||
API
|
||||
---
|
||||
|
||||
### Creating a node-static Server #
|
||||
|
||||
Creating a file server instance is as simple as:
|
||||
|
||||
```js
|
||||
new static.Server();
|
||||
```
|
||||
|
||||
This will serve files in the current directory. If you want to serve files in a specific
|
||||
directory, pass it as the first argument:
|
||||
|
||||
```js
|
||||
new static.Server('./public');
|
||||
```
|
||||
|
||||
You can also specify how long the client is supposed to cache the files node-static serves:
|
||||
|
||||
```js
|
||||
new static.Server('./public', { cache: 3600 });
|
||||
```
|
||||
|
||||
This will set the `Cache-Control` header, telling clients to cache the file for an hour.
|
||||
This is the default setting.
|
||||
|
||||
### Serving files under a directory #
|
||||
|
||||
To serve files under a directory, simply call the `serve` method on a `Server` instance, passing it
|
||||
the HTTP request and response object:
|
||||
|
||||
```js
|
||||
var static = require('node-static');
|
||||
|
||||
var fileServer = new static.Server('./public');
|
||||
|
||||
require('http').createServer(function (request, response) {
|
||||
request.addListener('end', function () {
|
||||
fileServer.serve(request, response);
|
||||
}).resume();
|
||||
}).listen(8080);
|
||||
```
|
||||
|
||||
### Serving specific files #
|
||||
|
||||
If you want to serve a specific file, like an error page for example, use the `serveFile` method:
|
||||
|
||||
```js
|
||||
fileServer.serveFile('/error.html', 500, {}, request, response);
|
||||
```
|
||||
|
||||
This will serve the `error.html` file, from under the file root directory, with a `500` status code.
|
||||
For example, you could serve an error page, when the initial request wasn't found:
|
||||
|
||||
```js
|
||||
require('http').createServer(function (request, response) {
|
||||
request.addListener('end', function () {
|
||||
fileServer.serve(request, response, function (e, res) {
|
||||
if (e && (e.status === 404)) { // If the file wasn't found
|
||||
fileServer.serveFile('/not-found.html', 404, {}, request, response);
|
||||
}
|
||||
});
|
||||
}).resume();
|
||||
}).listen(8080);
|
||||
```
|
||||
|
||||
More on intercepting errors bellow.
|
||||
|
||||
### Intercepting errors & Listening #
|
||||
|
||||
An optional callback can be passed as last argument, it will be called every time a file
|
||||
has been served successfully, or if there was an error serving the file:
|
||||
|
||||
```js
|
||||
var static = require('node-static');
|
||||
|
||||
var fileServer = new static.Server('./public');
|
||||
|
||||
require('http').createServer(function (request, response) {
|
||||
request.addListener('end', function () {
|
||||
fileServer.serve(request, response, function (err, result) {
|
||||
if (err) { // There was an error serving the file
|
||||
console.error("Error serving " + request.url + " - " + err.message);
|
||||
|
||||
// Respond to the client
|
||||
response.writeHead(err.status, err.headers);
|
||||
response.end();
|
||||
}
|
||||
});
|
||||
}).resume();
|
||||
}).listen(8080);
|
||||
```
|
||||
|
||||
Note that if you pass a callback, and there is an error serving the file, node-static
|
||||
*will not* respond to the client. This gives you the opportunity to re-route the request,
|
||||
or handle it differently.
|
||||
|
||||
For example, you may want to interpret a request as a static request, but if the file isn't found,
|
||||
send it to an application.
|
||||
|
||||
If you only want to *listen* for errors, you can use *event listeners*:
|
||||
|
||||
```js
|
||||
fileServer.serve(request, response).addListener('error', function (err) {
|
||||
console.error("Error serving " + request.url + " - " + err.message);
|
||||
});
|
||||
```
|
||||
|
||||
With this method, you don't have to explicitly send the response back, in case of an error.
|
||||
|
||||
### Options when creating an instance of `Server` #
|
||||
|
||||
#### `cache` #
|
||||
|
||||
Sets the `Cache-Control` header.
|
||||
|
||||
example: `{ cache: 7200 }`
|
||||
|
||||
Passing a number will set the cache duration to that number of seconds.
|
||||
Passing `false` will disable the `Cache-Control` header.
|
||||
|
||||
> Defaults to `3600`
|
||||
|
||||
|
||||
#### `serverInfo` #
|
||||
|
||||
Sets the `Server` header.
|
||||
|
||||
example: `{ serverInfo: "myserver" }`
|
||||
|
||||
> Defaults to `node-static/{version}`
|
||||
|
||||
#### `headers` #
|
||||
|
||||
Sets response headers.
|
||||
|
||||
example: `{ 'X-Hello': 'World!' }`
|
||||
|
||||
> defaults to `{}`
|
||||
|
||||
#### `gzip` #
|
||||
|
||||
Enable support for sending compressed responses. This will enable a check for a
|
||||
file with the same name plus '.gz' in the same folder. If the compressed file is
|
||||
found and the client has indicated support for gzip file transfer, the contents
|
||||
of the .gz file will be sent in place of the uncompressed file along with a
|
||||
Content-Encoding: gzip header to inform the client the data has been compressed.
|
||||
|
||||
example: `{ gzip: true }`
|
||||
example: `{ gzip: /^\/text/ }`
|
||||
|
||||
Passing `true` will enable this check for all files.
|
||||
Passing a RegExp instance will only enable this check if the content-type of the
|
||||
respond would match that RegExp using its test() method.
|
||||
|
||||
> Defaults to `false`
|
||||
|
||||
#### `indexFile` #
|
||||
|
||||
Choose a custom index file when serving up directories.
|
||||
|
||||
example: `{ indexFile: "index.htm" }`
|
||||
|
||||
> Defaults to `index.html`
|
||||
|
||||
|
||||
Command Line Interface
|
||||
----------------------
|
||||
|
||||
`node-static` also provides a CLI.
|
||||
|
||||
### Installation #
|
||||
|
||||
```sh
|
||||
$ npm install -g node-static
|
||||
```
|
||||
|
||||
### Example Usage #
|
||||
|
||||
```sh
|
||||
# serve up the current directory
|
||||
$ static
|
||||
serving "." at http://127.0.0.1:8080
|
||||
|
||||
# serve up a different directory
|
||||
$ static public
|
||||
serving "public" at http://127.0.0.1:8080
|
||||
|
||||
# specify additional headers (this one is useful for development)
|
||||
$ static -H '{"Cache-Control": "no-cache, must-revalidate"}'
|
||||
serving "." at http://127.0.0.1:8080
|
||||
|
||||
# set cache control max age
|
||||
$ static -c 7200
|
||||
serving "." at http://127.0.0.1:8080
|
||||
|
||||
# expose the server to your local network
|
||||
$ static -a 0.0.0.0
|
||||
serving "." at http://0.0.0.0:8080
|
||||
|
||||
# show help message, including all options
|
||||
$ static -h
|
||||
```
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
This is ApacheBench, Version 2.3 <$Revision: 655654 $>
|
||||
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
|
||||
Licensed to The Apache Software Foundation, http://www.apache.org/
|
||||
|
||||
Benchmarking 127.0.0.1 (be patient)
|
||||
|
||||
|
||||
Server Software: node-static/0.3.0
|
||||
Server Hostname: 127.0.0.1
|
||||
Server Port: 8080
|
||||
|
||||
Document Path: /lib/node-static.js
|
||||
Document Length: 6038 bytes
|
||||
|
||||
Concurrency Level: 20
|
||||
Time taken for tests: 2.323 seconds
|
||||
Complete requests: 10000
|
||||
Failed requests: 0
|
||||
Write errors: 0
|
||||
Total transferred: 63190000 bytes
|
||||
HTML transferred: 60380000 bytes
|
||||
Requests per second: 4304.67 [#/sec] (mean)
|
||||
Time per request: 4.646 [ms] (mean)
|
||||
Time per request: 0.232 [ms] (mean, across all concurrent requests)
|
||||
Transfer rate: 26563.66 [Kbytes/sec] received
|
||||
|
||||
Connection Times (ms)
|
||||
min mean[+/-sd] median max
|
||||
Connect: 0 0 0.2 0 3
|
||||
Processing: 1 4 1.4 4 28
|
||||
Waiting: 1 4 1.3 4 18
|
||||
Total: 2 5 1.5 4 28
|
||||
|
||||
Percentage of the requests served within a certain time (ms)
|
||||
50% 4
|
||||
66% 5
|
||||
75% 5
|
||||
80% 5
|
||||
90% 5
|
||||
95% 6
|
||||
98% 8
|
||||
99% 9
|
||||
100% 28 (longest request)
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
var fs = require('fs'),
|
||||
path = require('path'),
|
||||
tty = require('tty'),
|
||||
statik = require('./../lib/node-static');
|
||||
|
||||
var argv = require('optimist')
|
||||
.usage([
|
||||
'USAGE: $0 [-p <port>] [<directory>]',
|
||||
'simple, rfc 2616 compliant file streaming module for node']
|
||||
.join('\n\n'))
|
||||
.option('port', {
|
||||
alias: 'p',
|
||||
'default': 8080,
|
||||
description: 'TCP port at which the files will be served'
|
||||
})
|
||||
.option('host-address', {
|
||||
alias: 'a',
|
||||
'default': '127.0.0.1',
|
||||
description: 'the local network interface at which to listen'
|
||||
})
|
||||
.option('cache', {
|
||||
alias: 'c',
|
||||
description: '"Cache-Control" header setting, defaults to 3600'
|
||||
})
|
||||
.option('version', {
|
||||
alias: 'v',
|
||||
description: 'node-static version'
|
||||
})
|
||||
.option('headers', {
|
||||
alias: 'H',
|
||||
description: 'additional headers (in JSON format)'
|
||||
})
|
||||
.option('header-file', {
|
||||
alias: 'f',
|
||||
description: 'JSON file of additional headers'
|
||||
})
|
||||
.option('gzip', {
|
||||
alias: 'z',
|
||||
description: 'enable compression (tries to serve file of same name plus \'.gz\')'
|
||||
})
|
||||
.option('spa', {
|
||||
description: 'serve the content as a single page app by redirecting all non-file requests to the index html file'
|
||||
})
|
||||
.option('indexFile', {
|
||||
alias: 'i',
|
||||
'default': 'index.html',
|
||||
description: 'specify a custom index file when serving up directories'
|
||||
})
|
||||
.option('help', {
|
||||
alias: 'h',
|
||||
description: 'display this help message'
|
||||
})
|
||||
.argv;
|
||||
|
||||
var dir = argv._[0] || '.';
|
||||
|
||||
var colors = require('colors');
|
||||
|
||||
var log = function(request, response, statusCode) {
|
||||
var d = new Date();
|
||||
var seconds = d.getSeconds() < 10? '0'+d.getSeconds() : d.getSeconds(),
|
||||
datestr = d.getHours() + ':' + d.getMinutes() + ':' + seconds,
|
||||
line = datestr + ' [' + response.statusCode + ']: ' + request.url,
|
||||
colorized = line;
|
||||
if (tty.isatty(process.stdout.fd))
|
||||
colorized = (response.statusCode >= 500) ? line.red.bold :
|
||||
(response.statusCode >= 400) ? line.red :
|
||||
line;
|
||||
console.log(colorized);
|
||||
};
|
||||
|
||||
var file, options;
|
||||
|
||||
if (argv.help) {
|
||||
require('optimist').showHelp(console.log);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (argv.version) {
|
||||
console.log('node-static', statik.version.join('.'));
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (argv.cache) {
|
||||
(options = options || {}).cache = argv.cache;
|
||||
}
|
||||
|
||||
if (argv.headers) {
|
||||
(options = options || {}).headers = JSON.parse(argv.headers);
|
||||
}
|
||||
|
||||
if (argv['header-file']) {
|
||||
(options = options || {}).headers =
|
||||
JSON.parse(fs.readFileSync(argv['header-file']));
|
||||
}
|
||||
|
||||
if (argv.gzip) {
|
||||
(options = options || {}).gzip = true;
|
||||
}
|
||||
|
||||
if (argv.indexFile) {
|
||||
(options = options || {}).indexFile = argv['indexFile'];
|
||||
}
|
||||
|
||||
file = new(statik.Server)(dir, options);
|
||||
|
||||
require('http').createServer(function (request, response) {
|
||||
request.addListener('end', function () {
|
||||
var callback = function(e, rsp) {
|
||||
if (e && e.status === 404) {
|
||||
response.writeHead(e.status, e.headers);
|
||||
response.end("Not Found");
|
||||
log(request, response);
|
||||
} else {
|
||||
log(request, response);
|
||||
}
|
||||
};
|
||||
|
||||
if (argv['spa'] && request.url.indexOf(".") == -1) {
|
||||
file.serveFile(argv['indexFile'], 500, {}, request, response);
|
||||
} else {
|
||||
file.serve(request, response, callback);
|
||||
}
|
||||
}).resume();
|
||||
}).listen(+argv.port, argv['host-address']);
|
||||
|
||||
console.log('serving "' + dir + '" at http://' + argv['host-address'] + ':' + argv.port);
|
||||
if (argv.spa) {
|
||||
console.log('serving as a single page app (all non-file requests redirect to ' + argv['indexFile'] +')');
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
var static = require('../lib/node-static');
|
||||
|
||||
//
|
||||
// Create a node-static server to serve the current directory
|
||||
//
|
||||
var file = new static.Server('.', { cache: 7200, headers: {'X-Hello':'World!'} });
|
||||
|
||||
require('http').createServer(function (request, response) {
|
||||
file.serve(request, response, function (err, res) {
|
||||
if (err) { // An error as occured
|
||||
console.error("> Error serving " + request.url + " - " + err.message);
|
||||
response.writeHead(err.status, err.headers);
|
||||
response.end();
|
||||
} else { // The file was served successfully
|
||||
console.log("> " + request.url + " - " + res.message);
|
||||
}
|
||||
});
|
||||
}).listen(8080);
|
||||
|
||||
console.log("> node-static is listening on http://127.0.0.1:8080");
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
var fs = require('fs')
|
||||
, events = require('events')
|
||||
, buffer = require('buffer')
|
||||
, http = require('http')
|
||||
, url = require('url')
|
||||
, path = require('path')
|
||||
, mime = require('mime')
|
||||
, util = require('./node-static/util');
|
||||
|
||||
// Current version
|
||||
var version = [0, 7, 9];
|
||||
|
||||
var Server = function (root, options) {
|
||||
if (root && (typeof(root) === 'object')) { options = root; root = null }
|
||||
|
||||
// resolve() doesn't normalize (to lowercase) drive letters on Windows
|
||||
this.root = path.normalize(path.resolve(root || '.'));
|
||||
this.options = options || {};
|
||||
this.cache = 3600;
|
||||
|
||||
this.defaultHeaders = {};
|
||||
this.options.headers = this.options.headers || {};
|
||||
|
||||
this.options.indexFile = this.options.indexFile || "index.html";
|
||||
|
||||
if ('cache' in this.options) {
|
||||
if (typeof(this.options.cache) === 'number') {
|
||||
this.cache = this.options.cache;
|
||||
} else if (! this.options.cache) {
|
||||
this.cache = false;
|
||||
}
|
||||
}
|
||||
|
||||
if ('serverInfo' in this.options) {
|
||||
this.serverInfo = this.options.serverInfo.toString();
|
||||
} else {
|
||||
this.serverInfo = 'node-static/' + version.join('.');
|
||||
}
|
||||
|
||||
this.defaultHeaders['server'] = this.serverInfo;
|
||||
|
||||
if (this.cache !== false) {
|
||||
this.defaultHeaders['cache-control'] = 'max-age=' + this.cache;
|
||||
}
|
||||
|
||||
for (var k in this.defaultHeaders) {
|
||||
this.options.headers[k] = this.options.headers[k] ||
|
||||
this.defaultHeaders[k];
|
||||
}
|
||||
};
|
||||
|
||||
Server.prototype.serveDir = function (pathname, req, res, finish) {
|
||||
var htmlIndex = path.join(pathname, this.options.indexFile),
|
||||
that = this;
|
||||
|
||||
fs.stat(htmlIndex, function (e, stat) {
|
||||
if (!e) {
|
||||
var status = 200;
|
||||
var headers = {};
|
||||
var originalPathname = decodeURI(url.parse(req.url).pathname);
|
||||
if (originalPathname.length && originalPathname.charAt(originalPathname.length - 1) !== '/') {
|
||||
return finish(301, { 'Location': originalPathname + '/' });
|
||||
} else {
|
||||
that.respond(null, status, headers, [htmlIndex], stat, req, res, finish);
|
||||
}
|
||||
} else {
|
||||
// Stream a directory of files as a single file.
|
||||
fs.readFile(path.join(pathname, 'index.json'), function (e, contents) {
|
||||
if (e) { return finish(404, {}) }
|
||||
var index = JSON.parse(contents);
|
||||
streamFiles(index.files);
|
||||
});
|
||||
}
|
||||
});
|
||||
function streamFiles(files) {
|
||||
util.mstat(pathname, files, function (e, stat) {
|
||||
if (e) { return finish(404, {}) }
|
||||
that.respond(pathname, 200, {}, files, stat, req, res, finish);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Server.prototype.serveFile = function (pathname, status, headers, req, res) {
|
||||
var that = this;
|
||||
var promise = new(events.EventEmitter);
|
||||
|
||||
pathname = this.resolve(pathname);
|
||||
|
||||
fs.stat(pathname, function (e, stat) {
|
||||
if (e) {
|
||||
return promise.emit('error', e);
|
||||
}
|
||||
that.respond(null, status, headers, [pathname], stat, req, res, function (status, headers) {
|
||||
that.finish(status, headers, req, res, promise);
|
||||
});
|
||||
});
|
||||
return promise;
|
||||
};
|
||||
|
||||
Server.prototype.finish = function (status, headers, req, res, promise, callback) {
|
||||
var result = {
|
||||
status: status,
|
||||
headers: headers,
|
||||
message: http.STATUS_CODES[status]
|
||||
};
|
||||
|
||||
headers['server'] = this.serverInfo;
|
||||
|
||||
if (!status || status >= 400) {
|
||||
if (callback) {
|
||||
callback(result);
|
||||
} else {
|
||||
if (promise.listeners('error').length > 0) {
|
||||
promise.emit('error', result);
|
||||
}
|
||||
else {
|
||||
res.writeHead(status, headers);
|
||||
res.end();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Don't end the request here, if we're streaming;
|
||||
// it's taken care of in `prototype.stream`.
|
||||
if (status !== 200 || req.method !== 'GET') {
|
||||
res.writeHead(status, headers);
|
||||
res.end();
|
||||
}
|
||||
callback && callback(null, result);
|
||||
promise.emit('success', result);
|
||||
}
|
||||
};
|
||||
|
||||
Server.prototype.servePath = function (pathname, status, headers, req, res, finish) {
|
||||
var that = this,
|
||||
promise = new(events.EventEmitter);
|
||||
|
||||
pathname = this.resolve(pathname);
|
||||
|
||||
// Make sure we're not trying to access a
|
||||
// file outside of the root.
|
||||
if (pathname.indexOf(that.root) === 0) {
|
||||
fs.stat(pathname, function (e, stat) {
|
||||
if (e) {
|
||||
finish(404, {});
|
||||
} else if (stat.isFile()) { // Stream a single file.
|
||||
that.respond(null, status, headers, [pathname], stat, req, res, finish);
|
||||
} else if (stat.isDirectory()) { // Stream a directory of files.
|
||||
that.serveDir(pathname, req, res, finish);
|
||||
} else {
|
||||
finish(400, {});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Forbidden
|
||||
finish(403, {});
|
||||
}
|
||||
return promise;
|
||||
};
|
||||
|
||||
Server.prototype.resolve = function (pathname) {
|
||||
return path.resolve(path.join(this.root, pathname));
|
||||
};
|
||||
|
||||
Server.prototype.serve = function (req, res, callback) {
|
||||
var that = this,
|
||||
promise = new(events.EventEmitter),
|
||||
pathname;
|
||||
|
||||
var finish = function (status, headers) {
|
||||
that.finish(status, headers, req, res, promise, callback);
|
||||
};
|
||||
|
||||
try {
|
||||
pathname = decodeURI(url.parse(req.url).pathname);
|
||||
}
|
||||
catch(e) {
|
||||
return process.nextTick(function() {
|
||||
return finish(400, {});
|
||||
});
|
||||
}
|
||||
|
||||
process.nextTick(function () {
|
||||
that.servePath(pathname, 200, {}, req, res, finish).on('success', function (result) {
|
||||
promise.emit('success', result);
|
||||
}).on('error', function (err) {
|
||||
promise.emit('error');
|
||||
});
|
||||
});
|
||||
if (! callback) { return promise }
|
||||
};
|
||||
|
||||
/* Check if we should consider sending a gzip version of the file based on the
|
||||
* file content type and client's Accept-Encoding header value.
|
||||
*/
|
||||
Server.prototype.gzipOk = function(req, contentType) {
|
||||
var enable = this.options.gzip;
|
||||
if(enable &&
|
||||
(typeof enable === 'boolean' ||
|
||||
(contentType && (enable instanceof RegExp) && enable.test(contentType)))) {
|
||||
var acceptEncoding = req.headers['accept-encoding'];
|
||||
return acceptEncoding && acceptEncoding.indexOf("gzip") >= 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Send a gzipped version of the file if the options and the client indicate gzip is enabled and
|
||||
* we find a .gz file mathing the static resource requested.
|
||||
*/
|
||||
Server.prototype.respondGzip = function(pathname, status, contentType, _headers, files, stat, req, res, finish) {
|
||||
var that = this;
|
||||
if(files.length == 1 && this.gzipOk(req, contentType)) {
|
||||
var gzFile = files[0] + ".gz";
|
||||
fs.stat(gzFile, function(e, gzStat) {
|
||||
if(!e && gzStat.isFile()) {
|
||||
//console.log('Serving', gzFile, 'to gzip-capable client instead of', files[0], 'new size is', gzStat.size, 'uncompressed size', stat.size);
|
||||
var vary = _headers['Vary'];
|
||||
_headers['Vary'] = (vary && vary != 'Accept-Encoding'?vary+', ':'')+'Accept-Encoding';
|
||||
_headers['Content-Encoding'] = 'gzip';
|
||||
stat.size = gzStat.size;
|
||||
files = [gzFile];
|
||||
} else {
|
||||
//console.log('gzip file not found or error finding it', gzFile, String(e), stat.isFile());
|
||||
}
|
||||
that.respondNoGzip(pathname, status, contentType, _headers, files, stat, req, res, finish);
|
||||
});
|
||||
} else {
|
||||
// Client doesn't want gzip or we're sending multiple files
|
||||
that.respondNoGzip(pathname, status, contentType, _headers, files, stat, req, res, finish);
|
||||
}
|
||||
}
|
||||
|
||||
Server.prototype.parseByteRange = function(req, stat) {
|
||||
var byteRange = {
|
||||
from: 0,
|
||||
to: 0,
|
||||
valid: false
|
||||
}
|
||||
|
||||
var rangeHeader = req.headers['range'];
|
||||
var flavor = 'bytes=';
|
||||
|
||||
if (rangeHeader) {
|
||||
if (rangeHeader.indexOf(flavor) == 0 && rangeHeader.indexOf(',') == -1) {
|
||||
/* Parse */
|
||||
rangeHeader = rangeHeader.substr(flavor.length).split('-');
|
||||
byteRange.from = parseInt(rangeHeader[0]);
|
||||
byteRange.to = parseInt(rangeHeader[1]);
|
||||
|
||||
/* Replace empty fields of differential requests by absolute values */
|
||||
if (isNaN(byteRange.from) && !isNaN(byteRange.to)) {
|
||||
byteRange.from = stat.size - byteRange.to;
|
||||
byteRange.to = stat.size ? stat.size - 1 : 0;
|
||||
} else if (!isNaN(byteRange.from) && isNaN(byteRange.to)) {
|
||||
byteRange.to = stat.size ? stat.size - 1 : 0;
|
||||
}
|
||||
|
||||
/* General byte range validation */
|
||||
if (!isNaN(byteRange.from) && !!byteRange.to && 0 <= byteRange.from && byteRange.from < byteRange.to) {
|
||||
byteRange.valid = true;
|
||||
} else {
|
||||
console.warn("Request contains invalid range header: ", rangeHeader);
|
||||
}
|
||||
} else {
|
||||
console.warn("Request contains unsupported range header: ", rangeHeader);
|
||||
}
|
||||
}
|
||||
return byteRange;
|
||||
}
|
||||
|
||||
Server.prototype.respondNoGzip = function (pathname, status, contentType, _headers, files, stat, req, res, finish) {
|
||||
var mtime = Date.parse(stat.mtime),
|
||||
key = pathname || files[0],
|
||||
headers = {},
|
||||
clientETag = req.headers['if-none-match'],
|
||||
clientMTime = Date.parse(req.headers['if-modified-since']),
|
||||
startByte = 0,
|
||||
length = stat.size,
|
||||
byteRange = this.parseByteRange(req, stat);
|
||||
|
||||
/* Handle byte ranges */
|
||||
if (files.length == 1 && byteRange.valid) {
|
||||
if (byteRange.to < length) {
|
||||
|
||||
// Note: HTTP Range param is inclusive
|
||||
startByte = byteRange.from;
|
||||
length = byteRange.to - byteRange.from + 1;
|
||||
status = 206;
|
||||
|
||||
// Set Content-Range response header (we advertise initial resource size on server here (stat.size))
|
||||
headers['Content-Range'] = 'bytes ' + byteRange.from + '-' + byteRange.to + '/' + stat.size;
|
||||
|
||||
} else {
|
||||
byteRange.valid = false;
|
||||
console.warn("Range request exceeds file boundaries, goes until byte no", byteRange.to, "against file size of", length, "bytes");
|
||||
}
|
||||
}
|
||||
|
||||
/* In any case, check for unhandled byte range headers */
|
||||
if (!byteRange.valid && req.headers['range']) {
|
||||
console.error(new Error("Range request present but invalid, might serve whole file instead"));
|
||||
}
|
||||
|
||||
// Copy default headers
|
||||
for (var k in this.options.headers) { headers[k] = this.options.headers[k] }
|
||||
// Copy custom headers
|
||||
for (var k in _headers) { headers[k] = _headers[k] }
|
||||
|
||||
headers['Etag'] = JSON.stringify([stat.ino, stat.size, mtime].join('-'));
|
||||
headers['Date'] = new(Date)().toUTCString();
|
||||
headers['Last-Modified'] = new(Date)(stat.mtime).toUTCString();
|
||||
headers['Content-Type'] = contentType;
|
||||
headers['Content-Length'] = length;
|
||||
|
||||
for (var k in _headers) { headers[k] = _headers[k] }
|
||||
|
||||
// Conditional GET
|
||||
// If the "If-Modified-Since" or "If-None-Match" headers
|
||||
// match the conditions, send a 304 Not Modified.
|
||||
if ((clientMTime || clientETag) &&
|
||||
(!clientETag || clientETag === headers['Etag']) &&
|
||||
(!clientMTime || clientMTime >= mtime)) {
|
||||
// 304 response should not contain entity headers
|
||||
['Content-Encoding',
|
||||
'Content-Language',
|
||||
'Content-Length',
|
||||
'Content-Location',
|
||||
'Content-MD5',
|
||||
'Content-Range',
|
||||
'Content-Type',
|
||||
'Expires',
|
||||
'Last-Modified'].forEach(function(entityHeader) {
|
||||
delete headers[entityHeader];
|
||||
});
|
||||
finish(304, headers);
|
||||
} else {
|
||||
|
||||
res.writeHead(status, headers);
|
||||
|
||||
this.stream(key, files, length, startByte, res, function (e) {
|
||||
if (e) { return finish(500, {}) }
|
||||
finish(status, headers);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Server.prototype.respond = function (pathname, status, _headers, files, stat, req, res, finish) {
|
||||
var contentType = _headers['Content-Type'] ||
|
||||
mime.lookup(files[0]) ||
|
||||
'application/octet-stream';
|
||||
|
||||
if(this.options.gzip) {
|
||||
this.respondGzip(pathname, status, contentType, _headers, files, stat, req, res, finish);
|
||||
} else {
|
||||
this.respondNoGzip(pathname, status, contentType, _headers, files, stat, req, res, finish);
|
||||
}
|
||||
}
|
||||
|
||||
Server.prototype.stream = function (pathname, files, length, startByte, res, callback) {
|
||||
|
||||
(function streamFile(files, offset) {
|
||||
var file = files.shift();
|
||||
|
||||
if (file) {
|
||||
file = path.resolve(file) === path.normalize(file) ? file : path.join(pathname || '.', file);
|
||||
|
||||
// Stream the file to the client
|
||||
fs.createReadStream(file, {
|
||||
flags: 'r',
|
||||
mode: 0666,
|
||||
start: startByte,
|
||||
end: startByte + (length ? length - 1 : 0)
|
||||
}).on('data', function (chunk) {
|
||||
// Bounds check the incoming chunk and offset, as copying
|
||||
// a buffer from an invalid offset will throw an error and crash
|
||||
if (chunk.length && offset < length && offset >= 0) {
|
||||
offset += chunk.length;
|
||||
}
|
||||
}).on('close', function () {
|
||||
streamFile(files, offset);
|
||||
}).on('error', function (err) {
|
||||
callback(err);
|
||||
console.error(err);
|
||||
}).pipe(res, { end: false });
|
||||
} else {
|
||||
res.end();
|
||||
callback(null, offset);
|
||||
}
|
||||
})(files.slice(0), 0);
|
||||
};
|
||||
|
||||
// Exports
|
||||
exports.Server = Server;
|
||||
exports.version = version;
|
||||
exports.mime = mime;
|
||||
|
||||
|
||||
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
var fs = require('fs')
|
||||
, path = require('path');
|
||||
|
||||
exports.mstat = function (dir, files, callback) {
|
||||
(function mstat(files, stats) {
|
||||
var file = files.shift();
|
||||
|
||||
if (file) {
|
||||
fs.stat(path.join(dir, file), function (e, stat) {
|
||||
if (e) {
|
||||
callback(e);
|
||||
} else {
|
||||
mstat(files, stats.concat([stat]));
|
||||
}
|
||||
});
|
||||
} else {
|
||||
callback(null, {
|
||||
size: stats.reduce(function (total, stat) {
|
||||
return total + stat.size;
|
||||
}, 0),
|
||||
mtime: stats.reduce(function (latest, stat) {
|
||||
return latest > stat.mtime ? latest : stat.mtime;
|
||||
}, 0),
|
||||
ino: stats.reduce(function (total, stat) {
|
||||
return total + stat.ino;
|
||||
}, 0)
|
||||
});
|
||||
}
|
||||
})(files.slice(0), []);
|
||||
};
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
{
|
||||
"_args": [
|
||||
[
|
||||
{
|
||||
"raw": "node-static@^0.7.9",
|
||||
"scope": null,
|
||||
"escapedName": "node-static",
|
||||
"name": "node-static",
|
||||
"rawSpec": "^0.7.9",
|
||||
"spec": ">=0.7.9 <0.8.0",
|
||||
"type": "range"
|
||||
},
|
||||
"/brodocs"
|
||||
]
|
||||
],
|
||||
"_from": "node-static@>=0.7.9 <0.8.0",
|
||||
"_id": "node-static@0.7.9",
|
||||
"_inCache": true,
|
||||
"_location": "/node-static",
|
||||
"_nodeVersion": "5.3.0",
|
||||
"_npmOperationalInternal": {
|
||||
"host": "packages-16-east.internal.npmjs.com",
|
||||
"tmp": "tmp/node-static-0.7.9.tgz_1475325505196_0.3733088574372232"
|
||||
},
|
||||
"_npmUser": {
|
||||
"name": "cloudhead",
|
||||
"email": "self@cloudhead.net"
|
||||
},
|
||||
"_npmVersion": "3.3.12",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"raw": "node-static@^0.7.9",
|
||||
"scope": null,
|
||||
"escapedName": "node-static",
|
||||
"name": "node-static",
|
||||
"rawSpec": "^0.7.9",
|
||||
"spec": ">=0.7.9 <0.8.0",
|
||||
"type": "range"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/node-static/-/node-static-0.7.9.tgz",
|
||||
"_shasum": "9bb69fce2281f7ae3cd1fb983e9ea0ec0cd9fecb",
|
||||
"_shrinkwrap": null,
|
||||
"_spec": "node-static@^0.7.9",
|
||||
"_where": "/brodocs",
|
||||
"author": {
|
||||
"name": "Alexis Sellier",
|
||||
"email": "self@cloudhead.net"
|
||||
},
|
||||
"bin": {
|
||||
"static": "bin/cli.js"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/cloudhead/node-static/issues"
|
||||
},
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Pablo Cantero",
|
||||
"email": "pablo@pablocantero.com"
|
||||
},
|
||||
{
|
||||
"name": "Ionică Bizău",
|
||||
"email": "bizauionica@gmail.com"
|
||||
}
|
||||
],
|
||||
"dependencies": {
|
||||
"colors": ">=0.6.0",
|
||||
"mime": ">=1.2.9",
|
||||
"optimist": ">=0.3.4"
|
||||
},
|
||||
"description": "simple, compliant file streaming module for node",
|
||||
"devDependencies": {
|
||||
"request": "latest",
|
||||
"vows": "latest"
|
||||
},
|
||||
"directories": {
|
||||
"example": "examples",
|
||||
"test": "test"
|
||||
},
|
||||
"dist": {
|
||||
"shasum": "9bb69fce2281f7ae3cd1fb983e9ea0ec0cd9fecb",
|
||||
"tarball": "https://registry.npmjs.org/node-static/-/node-static-0.7.9.tgz"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.4.1"
|
||||
},
|
||||
"gitHead": "ab26244449c8bc5246327207f3f540a24cdc1705",
|
||||
"homepage": "https://github.com/cloudhead/node-static",
|
||||
"keywords": [
|
||||
"http",
|
||||
"static",
|
||||
"file",
|
||||
"server"
|
||||
],
|
||||
"license": "MIT",
|
||||
"main": "./lib/node-static",
|
||||
"maintainers": [
|
||||
{
|
||||
"name": "cloudhead",
|
||||
"email": "self@cloudhead.net"
|
||||
},
|
||||
{
|
||||
"name": "indexzero",
|
||||
"email": "charlie.robbins@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "phstc",
|
||||
"email": "pablo@pablocantero.com"
|
||||
}
|
||||
],
|
||||
"name": "node-static",
|
||||
"optionalDependencies": {},
|
||||
"readme": "ERROR: No README data found!",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+ssh://git@github.com/cloudhead/node-static.git"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "vows --spec --isolate"
|
||||
},
|
||||
"url": "http://github.com/cloudhead/node-static",
|
||||
"version": "0.7.9"
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
hello world
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Awesome page</title>
|
||||
</head>
|
||||
<body>
|
||||
hello world!
|
||||
</body>
|
||||
</html>
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>Other page</title>
|
||||
</head>
|
||||
<body>
|
||||
hello there!
|
||||
</body>
|
||||
</html>
|
||||
Generated
Vendored
+390
@@ -0,0 +1,390 @@
|
||||
var vows = require('vows')
|
||||
, request = require('request')
|
||||
, assert = require('assert')
|
||||
, static = require('../../lib/node-static');
|
||||
|
||||
var fileServer = new static.Server(__dirname + '/../fixtures');
|
||||
var suite = vows.describe('node-static');
|
||||
var TEST_PORT = 8080;
|
||||
var TEST_SERVER = 'http://localhost:' + TEST_PORT;
|
||||
var version = static.version.join('.');
|
||||
var server;
|
||||
var callback;
|
||||
|
||||
headers = {
|
||||
'requesting headers': {
|
||||
topic : function(){
|
||||
request.head(TEST_SERVER + '/index.html', this.callback);
|
||||
}
|
||||
}
|
||||
}
|
||||
headers['requesting headers']['should respond with node-static/' + version] = function(error, response, body){
|
||||
assert.equal(response.headers['server'], 'node-static/' + version);
|
||||
}
|
||||
|
||||
suite.addBatch({
|
||||
'once an http server is listening with a callback': {
|
||||
topic: function () {
|
||||
server = require('http').createServer(function (request, response) {
|
||||
fileServer.serve(request, response, function(err, result) {
|
||||
if (callback)
|
||||
callback(request, response, err, result);
|
||||
else
|
||||
request.end();
|
||||
});
|
||||
}).listen(TEST_PORT, this.callback)
|
||||
},
|
||||
'should be listening' : function(){
|
||||
/* This test is necessary to ensure the topic execution.
|
||||
* A topic without tests will be not executed */
|
||||
assert.isTrue(true);
|
||||
}
|
||||
},
|
||||
}).addBatch({
|
||||
'streaming a 404 page': {
|
||||
topic: function(){
|
||||
callback = function(request, response, err, result) {
|
||||
if (err) {
|
||||
response.writeHead(err.status, err.headers);
|
||||
setTimeout(function() {
|
||||
response.end('Custom 404 Stream.')
|
||||
}, 100);
|
||||
}
|
||||
}
|
||||
request.get(TEST_SERVER + '/not-found', this.callback);
|
||||
},
|
||||
'should respond with 404' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 404);
|
||||
},
|
||||
'should respond with the streamed content': function(error, response, body){
|
||||
callback = null;
|
||||
assert.equal(body, 'Custom 404 Stream.');
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'once an http server is listening without a callback': {
|
||||
topic: function () {
|
||||
server.close();
|
||||
server = require('http').createServer(function (request, response) {
|
||||
fileServer.serve(request, response);
|
||||
}).listen(TEST_PORT, this.callback)
|
||||
},
|
||||
'should be listening' : function(){
|
||||
/* This test is necessary to ensure the topic execution.
|
||||
* A topic without tests will be not executed */
|
||||
assert.isTrue(true);
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'requesting a file not found': {
|
||||
topic : function(){
|
||||
request.get(TEST_SERVER + '/not-found', this.callback);
|
||||
},
|
||||
'should respond with 404' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 404);
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'requesting a malformed URI': {
|
||||
topic: function(){
|
||||
request.get(TEST_SERVER + '/a%AFc', this.callback);
|
||||
},
|
||||
'should respond with 400': function(error, response, body){
|
||||
assert.equal(response.statusCode, 400);
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'serving empty.css': {
|
||||
topic : function(){
|
||||
request.get(TEST_SERVER + '/empty.css', this.callback);
|
||||
},
|
||||
'should respond with 200' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
},
|
||||
'should respond with text/css': function(error, response, body){
|
||||
assert.equal(response.headers['content-type'], 'text/css');
|
||||
},
|
||||
'should respond with empty string': function(error, response, body){
|
||||
assert.equal(body, '');
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'serving hello.txt': {
|
||||
topic : function(){
|
||||
request.get(TEST_SERVER + '/hello.txt', this.callback);
|
||||
},
|
||||
'should respond with 200' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
},
|
||||
'should respond with text/plain': function(error, response, body){
|
||||
assert.equal(response.headers['content-type'], 'text/plain');
|
||||
},
|
||||
'should respond with hello world': function(error, response, body){
|
||||
assert.equal(body, 'hello world');
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'serving first 5 bytes of hello.txt': {
|
||||
topic : function(){
|
||||
var options = {
|
||||
url: TEST_SERVER + '/hello.txt',
|
||||
headers: {
|
||||
'Range': 'bytes=0-4'
|
||||
}
|
||||
};
|
||||
request.get(options, this.callback);
|
||||
},
|
||||
'should respond with 206' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 206);
|
||||
},
|
||||
'should respond with text/plain': function(error, response, body){
|
||||
assert.equal(response.headers['content-type'], 'text/plain');
|
||||
},
|
||||
'should have content-length of 5 bytes': function(error, response, body){
|
||||
assert.equal(response.headers['content-length'], 5);
|
||||
},
|
||||
'should have a valid Content-Range header in response': function(error, response, body){
|
||||
assert.equal(response.headers['content-range'], 'bytes 0-4/11');
|
||||
},
|
||||
'should respond with hello': function(error, response, body){
|
||||
assert.equal(body, 'hello');
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'serving last 5 bytes of hello.txt': {
|
||||
topic : function(){
|
||||
var options = {
|
||||
url: TEST_SERVER + '/hello.txt',
|
||||
headers: {
|
||||
'Range': 'bytes=6-10'
|
||||
}
|
||||
};
|
||||
request.get(options, this.callback);
|
||||
},
|
||||
'should respond with 206' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 206);
|
||||
},
|
||||
'should respond with text/plain': function(error, response, body){
|
||||
assert.equal(response.headers['content-type'], 'text/plain');
|
||||
},
|
||||
'should have content-length of 5 bytes': function(error, response, body){
|
||||
assert.equal(response.headers['content-length'], 5);
|
||||
},
|
||||
'should have a valid Content-Range header in response': function(error, response, body){
|
||||
assert.equal(response.headers['content-range'], 'bytes 6-10/11');
|
||||
},
|
||||
'should respond with world': function(error, response, body){
|
||||
assert.equal(body, 'world');
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'serving all from the start of hello.txt': {
|
||||
topic : function(){
|
||||
var options = {
|
||||
url: TEST_SERVER + '/hello.txt',
|
||||
headers: {
|
||||
'Range': 'bytes=0-'
|
||||
}
|
||||
};
|
||||
request.get(options, this.callback);
|
||||
},
|
||||
'should respond with 206' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 206);
|
||||
},
|
||||
'should respond with text/plain': function(error, response, body){
|
||||
assert.equal(response.headers['content-type'], 'text/plain');
|
||||
},
|
||||
'should have content-length of 11 bytes': function(error, response, body){
|
||||
assert.equal(response.headers['content-length'], 11);
|
||||
},
|
||||
'should have a valid Content-Range header in response': function(error, response, body){
|
||||
assert.equal(response.headers['content-range'], 'bytes 0-10/11');
|
||||
},
|
||||
'should respond with "hello world"': function(error, response, body){
|
||||
assert.equal(body, 'hello world');
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'serving directory index': {
|
||||
topic : function(){
|
||||
request.get(TEST_SERVER, this.callback);
|
||||
},
|
||||
'should respond with 200' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
},
|
||||
'should respond with text/html': function(error, response, body){
|
||||
assert.equal(response.headers['content-type'], 'text/html');
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'serving index.html from the cache': {
|
||||
topic : function(){
|
||||
request.get(TEST_SERVER + '/index.html', this.callback);
|
||||
},
|
||||
'should respond with 200' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
},
|
||||
'should respond with text/html': function(error, response, body){
|
||||
assert.equal(response.headers['content-type'], 'text/html');
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'requesting with If-None-Match': {
|
||||
topic : function(){
|
||||
var _this = this;
|
||||
request.get(TEST_SERVER + '/index.html', function(error, response, body){
|
||||
request({
|
||||
method: 'GET',
|
||||
uri: TEST_SERVER + '/index.html',
|
||||
headers: {'if-none-match': response.headers['etag']}
|
||||
},
|
||||
_this.callback);
|
||||
});
|
||||
},
|
||||
'should respond with 304' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 304);
|
||||
}
|
||||
},
|
||||
'requesting with If-None-Match and If-Modified-Since': {
|
||||
topic : function(){
|
||||
var _this = this;
|
||||
request.get(TEST_SERVER + '/index.html', function(error, response, body){
|
||||
var modified = Date.parse(response.headers['last-modified']);
|
||||
var oneDayLater = new Date(modified + (24 * 60 * 60 * 1000)).toUTCString();
|
||||
var nonMatchingEtag = '1111222233334444';
|
||||
request({
|
||||
method: 'GET',
|
||||
uri: TEST_SERVER + '/index.html',
|
||||
headers: {
|
||||
'if-none-match': nonMatchingEtag,
|
||||
'if-modified-since': oneDayLater
|
||||
}
|
||||
},
|
||||
_this.callback);
|
||||
});
|
||||
},
|
||||
'should respond with a 200': function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'requesting POST': {
|
||||
topic : function(){
|
||||
request.post(TEST_SERVER + '/index.html', this.callback);
|
||||
},
|
||||
'should respond with 200' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
},
|
||||
'should not be empty' : function(error, response, body){
|
||||
assert.isNotEmpty(body);
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'requesting HEAD': {
|
||||
topic : function(){
|
||||
request.head(TEST_SERVER + '/index.html', this.callback);
|
||||
},
|
||||
'should respond with 200' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
},
|
||||
'head must has no body' : function(error, response, body){
|
||||
assert.isEmpty(body);
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch(headers)
|
||||
.addBatch({
|
||||
'addings custom mime types': {
|
||||
topic : function(){
|
||||
static.mime.define({'application/font-woff': ['woff']});
|
||||
this.callback();
|
||||
},
|
||||
'should add woff' : function(error, response, body){
|
||||
assert.equal(static.mime.lookup('woff'), 'application/font-woff');
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'serving subdirectory index': {
|
||||
topic : function(){
|
||||
request.get(TEST_SERVER + '/there/', this.callback); // with trailing slash
|
||||
},
|
||||
'should respond with 200' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
},
|
||||
'should respond with text/html': function(error, response, body){
|
||||
assert.equal(response.headers['content-type'], 'text/html');
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'redirecting to subdirectory index': {
|
||||
topic : function(){
|
||||
request.get({ url: TEST_SERVER + '/there', followRedirect: false }, this.callback); // without trailing slash
|
||||
},
|
||||
'should respond with 301' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 301);
|
||||
},
|
||||
'should respond with location header': function(error, response, body){
|
||||
assert.equal(response.headers['location'], '/there/'); // now with trailing slash
|
||||
},
|
||||
'should respond with empty string body' : function(error, response, body){
|
||||
assert.equal(body, '');
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'requesting a subdirectory (with trailing slash) not found': {
|
||||
topic : function(){
|
||||
request.get(TEST_SERVER + '/notthere/', this.callback); // with trailing slash
|
||||
},
|
||||
'should respond with 404' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 404);
|
||||
}
|
||||
}
|
||||
})
|
||||
.addBatch({
|
||||
'requesting a subdirectory (without trailing slash) not found': {
|
||||
topic : function(){
|
||||
request.get({ url: TEST_SERVER + '/notthere', followRedirect: false }, this.callback); // without trailing slash
|
||||
},
|
||||
'should respond with 404' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 404);
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'once an http server is listening with custom index configuration': {
|
||||
topic: function () {
|
||||
server.close();
|
||||
|
||||
fileServer = new static.Server(__dirname + '/../fixtures', { indexFile: "hello.txt" });
|
||||
|
||||
server = require('http').createServer(function (request, response) {
|
||||
fileServer.serve(request, response);
|
||||
}).listen(TEST_PORT, this.callback)
|
||||
},
|
||||
'should be listening' : function(){
|
||||
/* This test is necessary to ensure the topic execution.
|
||||
* A topic without tests will be not executed */
|
||||
assert.isTrue(true);
|
||||
}
|
||||
}
|
||||
}).addBatch({
|
||||
'serving custom index file': {
|
||||
topic : function(){
|
||||
request.get(TEST_SERVER + '/', this.callback);
|
||||
},
|
||||
'should respond with 200' : function(error, response, body){
|
||||
assert.equal(response.statusCode, 200);
|
||||
},
|
||||
'should respond with empty string': function(error, response, body){
|
||||
assert.equal(body, 'hello world');
|
||||
}
|
||||
}
|
||||
}).export(module);
|
||||
|
||||
Reference in New Issue
Block a user