Browse Source

switch to js standard style

master
Lloyd Brookes 9 years ago
parent
commit
867275a29d
  1. 2
      README.md
  2. 153
      bin/ws.js
  3. 30
      lib/cli-options.js

2
README.md

@ -1,7 +1,7 @@
[![view on npm](http://img.shields.io/npm/v/local-web-server.svg)](https://www.npmjs.org/package/local-web-server) [![view on npm](http://img.shields.io/npm/v/local-web-server.svg)](https://www.npmjs.org/package/local-web-server)
[![npm module downloads per month](http://img.shields.io/npm/dm/local-web-server.svg)](https://www.npmjs.org/package/local-web-server) [![npm module downloads per month](http://img.shields.io/npm/dm/local-web-server.svg)](https://www.npmjs.org/package/local-web-server)
[![Dependency Status](https://david-dm.org/75lb/local-web-server.svg)](https://david-dm.org/75lb/local-web-server) [![Dependency Status](https://david-dm.org/75lb/local-web-server.svg)](https://david-dm.org/75lb/local-web-server)
![Analytics](https://ga-beacon.appspot.com/UA-27725889-12/local-web-server/README.md?pixel)
[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](https://github.com/feross/standard)
# local-web-server # local-web-server
Fires up a simple, CORS-enabled, static web server on a given port. Use for local web development or file sharing (directory browsing enabled). Fires up a simple, CORS-enabled, static web server on a given port. Use for local web development or file sharing (directory browsing enabled).

153
bin/ws.js

@ -1,46 +1,45 @@
#!/usr/bin/env node #!/usr/bin/env node
"use strict";
var dope = require("console-dope");
var http = require("http");
var cliArgs = require("command-line-args");
var o = require("object-tools");
var t = require("typical");
var path = require("path");
var loadConfig = require("config-master");
var homePath = require("home-path");
var logStats = require("stream-log-stats");
var connect = require("connect");
var morgan = require("morgan");
var serveStatic = require("serve-static");
var directory = require("serve-index");
var compress = require("compression");
var cliOptions = require("../lib/cli-options");
var url = require("url");
'use strict'
var dope = require('console-dope')
var http = require('http')
var cliArgs = require('command-line-args')
var o = require('object-tools')
var t = require('typical')
var path = require('path')
var loadConfig = require('config-master')
var homePath = require('home-path')
var logStats = require('stream-log-stats')
var connect = require('connect')
var morgan = require('morgan')
var serveStatic = require('serve-static')
var directory = require('serve-index')
var compress = require('compression')
var cliOptions = require('../lib/cli-options')
/* specify the command line arg definitions and usage forms */ /* specify the command line arg definitions and usage forms */
var cli = cliArgs(cliOptions);
var cli = cliArgs(cliOptions)
var usage = cli.getUsage({ var usage = cli.getUsage({
title: "local-web-server",
description: "Lightweight static web server, zero configuration.",
footer: "Project home: [underline]{https://github.com/75lb/local-web-server}",
title: 'local-web-server',
description: 'Lightweight static web server, zero configuration.',
footer: 'Project home: [underline]{https://github.com/75lb/local-web-server}',
usage: { usage: {
forms: [ forms: [
"$ ws <server options>",
"$ ws --config",
"$ ws --help"
'$ ws <server options>',
'$ ws --config',
'$ ws --help'
] ]
}, },
groups: { groups: {
server: "Server",
misc: "Misc"
server: 'Server',
misc: 'Misc'
} }
});
})
/* parse command line args */ /* parse command line args */
try { try {
var wsOptions = cli.parse();
var wsOptions = cli.parse()
} catch (err) { } catch (err) {
halt(err.message);
halt(err.message)
} }
/* Load and merge together options from /* Load and merge together options from
@ -49,110 +48,108 @@ try {
- the `local-web-server` property of {cwd}/package.json - the `local-web-server` property of {cwd}/package.json
*/ */
var storedConfig = loadConfig( var storedConfig = loadConfig(
path.join(homePath(), ".local-web-server.json"),
path.join(process.cwd(), ".local-web-server.json"),
{ jsonPath: path.join(process.cwd(), "package.json"), configProperty: "local-web-server" }
);
path.join(homePath(), '.local-web-server.json'),
path.join(process.cwd(), '.local-web-server.json'),
{ jsonPath: path.join(process.cwd(), 'package.json'), configProperty: 'local-web-server' }
)
var builtInDefaults = { var builtInDefaults = {
port: 8000, port: 8000,
directory: process.cwd(), directory: process.cwd(),
"refresh-rate": 500,
'refresh-rate': 500,
mime: {} mime: {}
};
}
/* override built-in defaults with stored config and then command line args */ /* override built-in defaults with stored config and then command line args */
wsOptions.server = o.extend(builtInDefaults, storedConfig, wsOptions.server);
wsOptions.server = o.extend(builtInDefaults, storedConfig, wsOptions.server)
/* user input validation */ /* user input validation */
if (!t.isNumber(wsOptions.server.port)) { if (!t.isNumber(wsOptions.server.port)) {
halt("please supply a numeric port value");
halt('please supply a numeric port value')
} }
if (wsOptions.misc.config) { if (wsOptions.misc.config) {
dope.log("Stored config: ");
dope.log(storedConfig);
process.exit(0);
dope.log('Stored config: ')
dope.log(storedConfig)
process.exit(0)
} else if (wsOptions.misc.help) { } else if (wsOptions.misc.help) {
dope.log(usage);
dope.log(usage)
} else { } else {
process.on("SIGINT", function(){
dope.showCursor();
dope.log();
process.exit(0);
});
process.on('SIGINT', function () {
dope.showCursor()
dope.log()
process.exit(0)
})
dope.hideCursor();
launchServer();
dope.hideCursor()
launchServer()
/* write launch information to stderr (stdout is reserved for web log output) */ /* write launch information to stderr (stdout is reserved for web log output) */
if (path.resolve(wsOptions.server.directory) === process.cwd()) { if (path.resolve(wsOptions.server.directory) === process.cwd()) {
dope.error("serving at %underline{%s}", "http://localhost:" + wsOptions.server.port);
dope.error('serving at %underline{%s}', 'http://localhost:' + wsOptions.server.port)
} else { } else {
dope.error("serving %underline{%s} at %underline{%s}", wsOptions.server.directory, "http://localhost:" + wsOptions.server.port);
dope.error('serving %underline{%s} at %underline{%s}', wsOptions.server.directory, 'http://localhost:' + wsOptions.server.port)
} }
} }
function halt (message) { function halt (message) {
dope.red.log("Error: %s", message);
dope.log(usage);
process.exit(1);
dope.red.log('Error: %s', message)
dope.log(usage)
process.exit(1)
} }
function launchServer () { function launchServer () {
var app = connect();
var app = connect()
/* enable cross-origin requests on all resources */ /* enable cross-origin requests on all resources */
app.use(function (req, res, next) { app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
next();
});
res.setHeader('Access-Control-Allow-Origin', '*')
next()
})
if (wsOptions.server["log-format"] !== "none") app.use(getLogger());
if (wsOptions.server['log-format'] !== 'none') app.use(getLogger())
/* --compress enables compression */ /* --compress enables compression */
if (wsOptions.server.compress) app.use(compress());
if (wsOptions.server.compress) app.use(compress())
/* set the mime-type overrides specified in the config */ /* set the mime-type overrides specified in the config */
serveStatic.mime.define(wsOptions.server.mime);
serveStatic.mime.define(wsOptions.server.mime)
/* enable static file server, including directory browsing support */ /* enable static file server, including directory browsing support */
app.use(serveStatic(path.resolve(wsOptions.server.directory))) app.use(serveStatic(path.resolve(wsOptions.server.directory)))
.use(directory(path.resolve(wsOptions.server.directory), { icons: true }));
.use(directory(path.resolve(wsOptions.server.directory), { icons: true }))
/* launch server */ /* launch server */
http.createServer(app) http.createServer(app)
.on("error", function(err){
if (err.code === "EADDRINUSE"){
halt("port " + wsOptions.server.port + " is already is use");
.on('error', function (err) {
if (err.code === 'EADDRINUSE') {
halt('port ' + wsOptions.server.port + ' is already is use')
} else { } else {
halt(err.message);
halt(err.message)
} }
}) })
.listen(wsOptions.server.port);
.listen(wsOptions.server.port)
} }
function getLogger () { function getLogger () {
/* log using --log-format (if supplied) */ /* log using --log-format (if supplied) */
var logFormat = wsOptions.server["log-format"];
var logFormat = wsOptions.server['log-format']
if (logFormat) { if (logFormat) {
if (logFormat === "logstalgia"){
if (logFormat === 'logstalgia') {
/* customised logger :date token, purely to satisfy Logstalgia. */ /* customised logger :date token, purely to satisfy Logstalgia. */
morgan.token("date", function(){
var d = new Date();
return (d.getDate() + "/" + d.getUTCMonth() + "/" + d.getFullYear() + ":" + d.toTimeString())
.replace("GMT", "").replace(" (BST)", "");
});
logFormat = "combined";
morgan.token('date', function () {
var d = new Date()
return (d.getDate() + '/' + d.getUTCMonth() + '/' + d.getFullYear() + ':' + d.toTimeString())
.replace('GMT', '').replace(' (BST)', '')
})
logFormat = 'combined'
} }
return morgan(logFormat);
return morgan(logFormat)
/* if no `--log-format` was specified, pipe the default format output /* if no `--log-format` was specified, pipe the default format output
into `log-stats`, which prints statistics to the console */ into `log-stats`, which prints statistics to the console */
} else { } else {
return morgan("common", { stream: logStats({ refreshRate: wsOptions.server["refresh-rate"] }) });
return morgan('common', { stream: logStats({ refreshRate: wsOptions.server['refresh-rate'] }) })
} }
} }

30
lib/cli-options.js

@ -1,30 +1,30 @@
module.exports = [ module.exports = [
{ {
name: "port", alias: "p", type: Number, defaultOption: true,
description: "Web server port", group: "server"
name: 'port', alias: 'p', type: Number, defaultOption: true,
description: 'Web server port', group: 'server'
}, },
{ {
name: "log-format", alias: "f", type: String,
description: "If a format is supplied an access log is written to stdout. If not, a statistics view is displayed. Use a preset ('none', 'dev','combined', 'short', 'tiny' or 'logstalgia') or supply a custom format (e.g. ':method -> :url').", group: "server"
name: 'log-format', alias: 'f', type: String,
description: "If a format is supplied an access log is written to stdout. If not, a statistics view is displayed. Use a preset ('none', 'dev','combined', 'short', 'tiny' or 'logstalgia') or supply a custom format (e.g. ':method -> :url').", group: 'server'
}, },
{ {
name: "directory", alias: "d", type: String,
description: "Root directory, defaults to the current directory", group: "server"
name: 'directory', alias: 'd', type: String,
description: 'Root directory, defaults to the current directory', group: 'server'
}, },
{ {
name: "compress", alias: "c", type: Boolean,
description: "Enable gzip compression, reduces bandwidth.", group: "server"
name: 'compress', alias: 'c', type: Boolean,
description: 'Enable gzip compression, reduces bandwidth.', group: 'server'
}, },
{ {
name: "refresh-rate", alias: "r", type: Number,
description: "Statistics view refresh rate in ms. Defaults to 500.", group: "server"
name: 'refresh-rate', alias: 'r', type: Number,
description: 'Statistics view refresh rate in ms. Defaults to 500.', group: 'server'
}, },
{ {
name: "help", alias: "h", type: Boolean,
description: "Print these usage instructions", group: "misc"
name: 'help', alias: 'h', type: Boolean,
description: 'Print these usage instructions', group: 'misc'
}, },
{ {
name: "config", type: Boolean,
description: "Print the stored config", group: "misc"
name: 'config', type: Boolean,
description: 'Print the stored config', group: 'misc'
} }
];
]
Loading…
Cancel
Save