3 var fs = require('fs'),
5 statik = require('./../lib/node-static');
7 var argv = require('optimist')
9 'USAGE: $0 [-p <port>] [<directory>]',
10 'simple, rfc 2616 compliant file streaming module for node']
15 description: 'TCP port at which the files will be served'
17 .option('host-address', {
19 'default': '127.0.0.1',
20 description: 'the local network interface at which to listen'
24 description: '"Cache-Control" header setting, defaults to 3600'
28 description: 'node-static version'
32 description: 'additional headers (in JSON format)'
34 .option('header-file', {
36 description: 'JSON file of additional headers'
40 description: 'enable compression (tries to serve file of same name plus \'.gz\')'
43 description: 'serve the content as a single page app by redirecting all non-file requests to the index html file'
45 .option('indexFile', {
47 'default': 'index.html',
48 description: 'specify a custom index file when serving up directories'
52 description: 'display this help message'
56 var dir = argv._[0] || '.';
58 var colors = require('colors');
60 var log = function(request, response, statusCode) {
62 var seconds = d.getSeconds() < 10? '0'+d.getSeconds() : d.getSeconds(),
63 datestr = d.getHours() + ':' + d.getMinutes() + ':' + seconds,
64 line = datestr + ' [' + response.statusCode + ']: ' + request.url,
66 if (tty.isatty(process.stdout.fd))
67 colorized = (response.statusCode >= 500) ? line.red.bold :
68 (response.statusCode >= 400) ? line.red :
70 console.log(colorized);
76 require('optimist').showHelp(console.log);
81 console.log('node-static', statik.version.join('.'));
86 (options = options || {}).cache = argv.cache;
90 (options = options || {}).headers = JSON.parse(argv.headers);
93 if (argv['header-file']) {
94 (options = options || {}).headers =
95 JSON.parse(fs.readFileSync(argv['header-file']));
99 (options = options || {}).gzip = true;
102 if (argv.indexFile) {
103 (options = options || {}).indexFile = argv['indexFile'];
106 file = new(statik.Server)(dir, options);
108 require('http').createServer(function (request, response) {
109 request.addListener('end', function () {
110 var callback = function(e, rsp) {
111 if (e && e.status === 404) {
112 response.writeHead(e.status, e.headers);
113 response.end("Not Found");
114 log(request, response);
116 log(request, response);
120 if (argv['spa'] && request.url.indexOf(".") == -1) {
121 file.serveFile(argv['indexFile'], 200, {}, request, response);
123 file.serve(request, response, callback);
126 }).listen(+argv.port, argv['host-address']);
128 console.log('serving "' + dir + '" at http://' + argv['host-address'] + ':' + argv.port);
130 console.log('serving as a single page app (all non-file requests redirect to ' + argv['indexFile'] +')');