let fs_readFile = util.promisify(fs.readFile)
-let Server = function() {
+let Server = function(resources, options) {
if (!this instanceof Server)
throw new Error('Server is a constructor')
+ this.resources = resources
+ this.options = {
+ caching: false,
+ listen: [
+ {
+ port: 8080
+ },
+ {
+ port: 8443,
+ protocol: 'https:'
+ }
+ ],
+ hosts: {
+ 'localhost': {
+ type: 'site',
+ root: 'site'
+ },
+ 'localhost.localdomain': {
+ type: 'redirect',
+ host: 'localhost'
+ }
+ }
+ }
+ if (options !== undefined)
+ Object.assign(this.options, options)
- this.enable_caching = false
- this.listen = []
- this.hosts = {}
- this.roots = {}
-
- this.resources = new Resources()
this.jst_cache = this.resources.ref(
'jst_cache:.',
() => new JSTCache('.', {_jst_server: jst_server}, true)
)
+ this.roots = {}
}
let compare_listen = (a, b) => {
if (config !== undefined) {
config = await config(this)
- this.enable_caching = config.enable_caching
+ this.options.caching = config.enable_caching
let listen = []
for (let i = 0; i < config.listen.length; ++i)
// stop all servers no longer in configuration file
let i = 0
let j = 0
- while (i < this.listen.length)
+ while (i < this.options.listen.length)
switch (
- j < this.listen.length ?
- compare_listen(this.listen[i], listen[j]) :
+ j < this.options.listen.length ?
+ compare_listen(this.options.listen[i], listen[j]) :
-1
) {
case -1:
- if (this.listen[i].server !== undefined) {
+ if (this.options.listen[i].server !== undefined) {
console.log(
- `stop listening on ${this.listen[i].protocol}//${this.listen[i].host}:${this.listen[i].port}`
+ `stop listening on ${this.options.listen[i].protocol}//${this.options.listen[i].host}:${this.options.listen[i].port}`
)
await new Promise(
(resolve, reject) => {
- this.listen[i].server.close(
+ this.options.listen[i].server.close(
err => {
if (err)
reject(err)
++i
break
case 0:
- listen[j++].server = this.listen[i++].server
+ listen[j++].server = this.options.listen[i++].server
break
case 1:
listen[j++].server = undefined // just to be on the safe side
listen[i].server = server
}
- this.listen = listen
+ this.options.listen = listen
- this.hosts = config.hosts
+ this.options.hosts = config.hosts
}
}
//console.log('parsed_url', parsed_url)
if (
- !Object.prototype.hasOwnProperty.call(this.hosts, parsed_url.hostname)
+ !Object.prototype.hasOwnProperty.call(this.options.hosts, parsed_url.hostname)
) {
this.die(
response,
return
}
- let host = this.hosts[parsed_url.hostname]
+ let host = this.options.hosts[parsed_url.hostname]
switch (host.type) {
case 'redirect':
let new_host = host.host
// must load index first, to avoid circular dependency issue
let index = require('./index')
+let Resources = require('./Resources')
let Server = require('./Server')
-let server = new Server()
+let server = new Server(new Resources())
// refresh the config immediately, then every 5 seconds,
// use setTimeout() instead of setInterval() to avoid bunches