summaryrefslogtreecommitdiffstats
path: root/lib/cli/server.js
blob: 555bbb7e9964131f94585cf275f1b272f053fad5 (plain)
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
var events = require('events');
var http = require('http');
var send = require('send');
var util = require('util');
var url = require('url');

var Promise = require('../utils/promise');

function Server() {
    this.running = null;
    this.dir = null;
    this.port = 0;
    this.sockets = [];
}
util.inherits(Server, events.EventEmitter);

/**
    Return true if the server is running

    @return {Boolean}
*/
Server.prototype.isRunning = function() {
    return !!this.running;
};

/**
    Stop the server

    @return {Promise}
*/
Server.prototype.stop = function() {
    var that = this;
    if (!this.isRunning()) return Promise();

    var d = Promise.defer();
    this.running.close(function(err) {
        that.running = null;
        that.emit('state', false);

        if (err) d.reject(err);
        else d.resolve();
    });

    for (var i = 0; i < this.sockets.length; i++) {
        this.sockets[i].destroy();
    }

    return d.promise;
};

/**
    Start the server

    @return {Promise}
*/
Server.prototype.start = function(dir, port) {
    var that = this, pre = Promise();
    port = port || 8004;

    if (that.isRunning()) pre = this.stop();
    return pre
    .then(function() {
        var d = Promise.defer();

        that.running = http.createServer(function(req, res){
            // Render error
            function error(err) {
                res.statusCode = err.status || 500;
                res.end(err.message);
            }

            // Redirect to directory's index.html
            function redirect() {
                res.statusCode = 301;
                res.setHeader('Location', req.url + '/');
                res.end('Redirecting to ' + req.url + '/');
            }

            // Send file
            send(req, url.parse(req.url).pathname, {
                root: dir
            })
            .on('error', error)
            .on('directory', redirect)
            .pipe(res);
        });

        that.running.on('connection', function (socket) {
            that.sockets.push(socket);
            socket.setTimeout(4000);
            socket.on('close', function () {
                that.sockets.splice(that.sockets.indexOf(socket), 1);
            });
        });

        that.running.listen(port, function(err) {
            if (err) return d.reject(err);

            that.port = port;
            that.dir = dir;
            that.emit('state', true);
            d.resolve();
        });

        return d.promise;
    });
};

module.exports = Server;