UNPKG

2.74 kBJavaScriptView Raw
1'use strict';
2
3var INHERIT = require('inherit'),
4 Q = require('q'),
5 QFS = require('q-io/fs'),
6 QS = require('querystring'),
7 QHTTP = require('q-io/http'),
8 URL = require('url'),
9 PATH = require('./path'),
10 LOGGER = require('./logger'),
11 Server = require('./base-server').Server,
12 U = require('./util');
13
14var assetsRoot = PATH.resolve(__dirname, 'data');
15
16exports.Server = INHERIT(Server, {
17
18 start: function() {
19
20 return this.rootExists(this.opts.root)()
21 .then(this.showInfo())
22 .then(this.startServers())
23 .then(function(servers) {
24 return Q.all(servers.map(function(s) {
25 return s.stopped;
26 }));
27 })
28 .then(function() {
29 LOGGER.info('Servers were stopped');
30 });
31
32 },
33
34 startServer: function(requestHandler) {
35 var _this = this,
36 netServer = QHTTP.Server(requestHandler),
37 started = [];
38
39 netServer.node.on('error', this.errorHandler.bind(this, this.opts['inspector-port']));
40
41 // Start server on net socket
42 started.push(netServer.listen(_this.opts['inspector-port'], _this.opts.host).then(function(listener) {
43
44 LOGGER.finfo('Inspector server is listening on port %s. Point your browser to http://localhost:%s/',
45 _this.opts['inspector-port'],
46 _this.opts['inspector-port']);
47
48 return listener;
49 }));
50
51 return started;
52 },
53
54 createRequestHandler: function(root) {
55 var _this = this;
56
57 return function(request, response) {
58
59 var reqPath = URL.parse(request.path).pathname,
60 relPath = QS.unescape(reqPath).replace(/^\/|\/$/g, ''),
61 fullPath = PATH.join(reqPath.toLowerCase().indexOf('/snapshots') === 0? PATH.join(root, '.bem'):assetsRoot, relPath);
62
63 LOGGER.fverbose('*** trying to access %s (%s)', fullPath, reqPath);
64
65 return _this.processPath(response, fullPath, root)();
66
67 };
68
69 },
70
71 processDirectory: function(response, path, root) {
72 return function() {
73 return QFS.list(path).then(function() {
74 response.status = 200;
75 response.charset = 'utf8';
76 response.headers = { 'content-type': 'text/json' };
77
78 root = PATH.join(root, '/');
79
80 var body = response.body = [],
81 files = [],
82 dirs = [];
83
84 body.push(U.getDirsFiles(path, dirs, files).then(function() {
85 return JSON.stringify(files);
86 }));
87
88 return response;
89 });
90 };
91 }
92});