@pattern-lab/live-server
Advanced tools
Comparing version
@@ -6,2 +6,21 @@ # Change Log | ||
<a name="1.3.3-alpha.2"></a> | ||
## [1.3.3-alpha.2](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/compare/@pattern-lab/live-server@1.3.3-alpha.1...@pattern-lab/live-server@1.3.3-alpha.2) (2018-03-21) | ||
### Bug Fixes | ||
* **lint:** run code through prettier ([ca52fde](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/commit/ca52fde)), closes [#825](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/issues/825) | ||
* **package:** remove files obsoleted by monorepo ([9abb8ac](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/commit/9abb8ac)) | ||
* **package:** update LICENSE ([337aa32](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/commit/337aa32)) | ||
* **README:** update content for consistency ([4edf0d4](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/commit/4edf0d4)), closes [#815](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/issues/815) | ||
### Features | ||
* **package:** standardize and hoist common devDependencies ([7f4ce6f](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/commit/7f4ce6f)) | ||
<a name="1.3.3-alpha.1"></a> | ||
@@ -8,0 +27,0 @@ ## [1.3.3-alpha.1](https://github.com/pattern-lab/patternlab-node/tree/master/packages/live-server/compare/@pattern-lab/live-server@1.3.3-alpha.0...@pattern-lab/live-server@1.3.3-alpha.1) (2018-03-05) |
744
index.js
#!/usr/bin/env node | ||
var fs = require('fs'), | ||
connect = require('connect'), | ||
serveIndex = require('serve-index'), | ||
logger = require('morgan'), | ||
WebSocket = require('faye-websocket'), | ||
path = require('path'), | ||
url = require('url'), | ||
http = require('http'), | ||
send = require('send'), | ||
open = require('opn'), | ||
es = require("event-stream"), | ||
os = require('os'), | ||
chokidar = require('chokidar'); | ||
connect = require('connect'), | ||
serveIndex = require('serve-index'), | ||
logger = require('morgan'), | ||
WebSocket = require('faye-websocket'), | ||
path = require('path'), | ||
url = require('url'), | ||
http = require('http'), | ||
send = require('send'), | ||
open = require('opn'), | ||
es = require('event-stream'), | ||
os = require('os'), | ||
chokidar = require('chokidar'); | ||
require('colors'); | ||
var INJECTED_CODE = fs.readFileSync(path.join(__dirname, "injected.html"), "utf8"); | ||
var INJECTED_CODE = fs.readFileSync( | ||
path.join(__dirname, 'injected.html'), | ||
'utf8' | ||
); | ||
var LiveServer = { | ||
server: null, | ||
watcher: null, | ||
logLevel: 2 | ||
server: null, | ||
watcher: null, | ||
logLevel: 2, | ||
}; | ||
function escape(html){ | ||
return String(html) | ||
.replace(/&(?!\w+;)/g, '&') | ||
.replace(/</g, '<') | ||
.replace(/>/g, '>') | ||
.replace(/"/g, '"'); | ||
function escape(html) { | ||
return String(html) | ||
.replace(/&(?!\w+;)/g, '&') | ||
.replace(/</g, '<') | ||
.replace(/>/g, '>') | ||
.replace(/"/g, '"'); | ||
} | ||
@@ -35,66 +38,82 @@ | ||
function staticServer(root) { | ||
var isFile = false; | ||
try { // For supporting mounting files instead of just directories | ||
isFile = fs.statSync(root).isFile(); | ||
} catch (e) { | ||
if (e.code !== "ENOENT") throw e; | ||
} | ||
return function(req, res, next) { | ||
if (req.method !== "GET" && req.method !== "HEAD") return next(); | ||
var reqpath = isFile ? "" : url.parse(req.url).pathname; | ||
var hasNoOrigin = !req.headers.origin; | ||
var injectCandidates = [ new RegExp("</body>", "i"), new RegExp("</svg>"), new RegExp("</head>", "i")]; | ||
var injectTag = null; | ||
var isFile = false; | ||
try { | ||
// For supporting mounting files instead of just directories | ||
isFile = fs.statSync(root).isFile(); | ||
} catch (e) { | ||
if (e.code !== 'ENOENT') throw e; | ||
} | ||
return function(req, res, next) { | ||
if (req.method !== 'GET' && req.method !== 'HEAD') return next(); | ||
var reqpath = isFile ? '' : url.parse(req.url).pathname; | ||
var hasNoOrigin = !req.headers.origin; | ||
var injectCandidates = [ | ||
new RegExp('</body>', 'i'), | ||
new RegExp('</svg>'), | ||
new RegExp('</head>', 'i'), | ||
]; | ||
var injectTag = null; | ||
function directory() { | ||
var pathname = url.parse(req.originalUrl).pathname; | ||
res.statusCode = 301; | ||
res.setHeader('Location', pathname + '/'); | ||
res.end('Redirecting to ' + escape(pathname) + '/'); | ||
} | ||
function directory() { | ||
var pathname = url.parse(req.originalUrl).pathname; | ||
res.statusCode = 301; | ||
res.setHeader('Location', pathname + '/'); | ||
res.end('Redirecting to ' + escape(pathname) + '/'); | ||
} | ||
function file(filepath /*, stat*/) { | ||
var x = path.extname(filepath).toLocaleLowerCase(), match, | ||
possibleExtensions = [ "", ".html", ".htm", ".xhtml", ".php", ".svg" ]; | ||
if (hasNoOrigin && (possibleExtensions.indexOf(x) > -1)) { | ||
// TODO: Sync file read here is not nice, but we need to determine if the html should be injected or not | ||
var contents = fs.readFileSync(filepath, "utf8"); | ||
for (var i = 0; i < injectCandidates.length; ++i) { | ||
match = injectCandidates[i].exec(contents); | ||
if (match) { | ||
injectTag = match[0]; | ||
break; | ||
} | ||
} | ||
if (injectTag === null && LiveServer.logLevel >= 3) { | ||
console.warn("Failed to inject refresh script!".yellow, | ||
"Couldn't find any of the tags ", injectCandidates, "from", filepath); | ||
} | ||
} | ||
} | ||
function file(filepath /*, stat*/) { | ||
var x = path.extname(filepath).toLocaleLowerCase(), | ||
match, | ||
possibleExtensions = ['', '.html', '.htm', '.xhtml', '.php', '.svg']; | ||
if (hasNoOrigin && possibleExtensions.indexOf(x) > -1) { | ||
// TODO: Sync file read here is not nice, but we need to determine if the html should be injected or not | ||
var contents = fs.readFileSync(filepath, 'utf8'); | ||
for (var i = 0; i < injectCandidates.length; ++i) { | ||
match = injectCandidates[i].exec(contents); | ||
if (match) { | ||
injectTag = match[0]; | ||
break; | ||
} | ||
} | ||
if (injectTag === null && LiveServer.logLevel >= 3) { | ||
console.warn( | ||
'Failed to inject refresh script!'.yellow, | ||
"Couldn't find any of the tags ", | ||
injectCandidates, | ||
'from', | ||
filepath | ||
); | ||
} | ||
} | ||
} | ||
function error(err) { | ||
if (err.status === 404) return next(); | ||
next(err); | ||
} | ||
function error(err) { | ||
if (err.status === 404) return next(); | ||
next(err); | ||
} | ||
function inject(stream) { | ||
if (injectTag) { | ||
// We need to modify the length given to browser | ||
var len = INJECTED_CODE.length + res.getHeader('Content-Length'); | ||
res.setHeader('Content-Length', len); | ||
var originalPipe = stream.pipe; | ||
stream.pipe = function(resp) { | ||
originalPipe.call(stream, es.replace(new RegExp(injectTag, "i"), INJECTED_CODE + injectTag)).pipe(resp); | ||
}; | ||
} | ||
} | ||
function inject(stream) { | ||
if (injectTag) { | ||
// We need to modify the length given to browser | ||
var len = INJECTED_CODE.length + res.getHeader('Content-Length'); | ||
res.setHeader('Content-Length', len); | ||
var originalPipe = stream.pipe; | ||
stream.pipe = function(resp) { | ||
originalPipe | ||
.call( | ||
stream, | ||
es.replace(new RegExp(injectTag, 'i'), INJECTED_CODE + injectTag) | ||
) | ||
.pipe(resp); | ||
}; | ||
} | ||
} | ||
send(req, reqpath, { root: root }) | ||
.on('error', error) | ||
.on('directory', directory) | ||
.on('file', file) | ||
.on('stream', inject) | ||
.pipe(res); | ||
}; | ||
send(req, reqpath, { root: root }) | ||
.on('error', error) | ||
.on('directory', directory) | ||
.on('file', file) | ||
.on('stream', inject) | ||
.pipe(res); | ||
}; | ||
} | ||
@@ -108,8 +127,11 @@ | ||
function entryPoint(staticHandler, file) { | ||
if (!file) return function(req, res, next) { next(); }; | ||
if (!file) | ||
return function(req, res, next) { | ||
next(); | ||
}; | ||
return function(req, res, next) { | ||
req.url = "/" + file; | ||
staticHandler(req, res, next); | ||
}; | ||
return function(req, res, next) { | ||
req.url = '/' + file; | ||
staticHandler(req, res, next); | ||
}; | ||
} | ||
@@ -135,288 +157,312 @@ | ||
LiveServer.start = function(options) { | ||
options = options || {}; | ||
var host = options.host || '0.0.0.0'; | ||
var port = options.port !== undefined ? options.port : 8080; // 0 means random | ||
var root = options.root || process.cwd(); | ||
var mount = options.mount || []; | ||
var watchPaths = options.watch || [root]; | ||
LiveServer.logLevel = options.logLevel === undefined ? 2 : options.logLevel; | ||
var openPath = (options.open === undefined || options.open === true) ? | ||
"" : ((options.open === null || options.open === false) ? null : options.open); | ||
if (options.noBrowser) openPath = null; // Backwards compatibility with 0.7.0 | ||
var file = options.file; | ||
var staticServerHandler = staticServer(root); | ||
var wait = options.wait === undefined ? 100 : options.wait; | ||
var browser = options.browser || null; | ||
var htpasswd = options.htpasswd || null; | ||
var cors = options.cors || false; | ||
var https = options.https || null; | ||
var proxy = options.proxy || []; | ||
var middleware = options.middleware || []; | ||
var noCssInject = options.noCssInject; | ||
var httpsModule = options.httpsModule; | ||
options = options || {}; | ||
var host = options.host || '0.0.0.0'; | ||
var port = options.port !== undefined ? options.port : 8080; // 0 means random | ||
var root = options.root || process.cwd(); | ||
var mount = options.mount || []; | ||
var watchPaths = options.watch || [root]; | ||
LiveServer.logLevel = options.logLevel === undefined ? 2 : options.logLevel; | ||
var openPath = | ||
options.open === undefined || options.open === true | ||
? '' | ||
: options.open === null || options.open === false ? null : options.open; | ||
if (options.noBrowser) openPath = null; // Backwards compatibility with 0.7.0 | ||
var file = options.file; | ||
var staticServerHandler = staticServer(root); | ||
var wait = options.wait === undefined ? 100 : options.wait; | ||
var browser = options.browser || null; | ||
var htpasswd = options.htpasswd || null; | ||
var cors = options.cors || false; | ||
var https = options.https || null; | ||
var proxy = options.proxy || []; | ||
var middleware = options.middleware || []; | ||
var noCssInject = options.noCssInject; | ||
var httpsModule = options.httpsModule; | ||
if (httpsModule) { | ||
try { | ||
require.resolve(httpsModule); | ||
} catch (e) { | ||
console.error(("HTTPS module \"" + httpsModule + "\" you've provided was not found.").red); | ||
console.error("Did you do", "\"npm install " + httpsModule + "\"?"); | ||
return; | ||
} | ||
} else { | ||
httpsModule = "https"; | ||
} | ||
if (httpsModule) { | ||
try { | ||
require.resolve(httpsModule); | ||
} catch (e) { | ||
console.error( | ||
('HTTPS module "' + httpsModule + '" you\'ve provided was not found.') | ||
.red | ||
); | ||
console.error('Did you do', '"npm install ' + httpsModule + '"?'); | ||
return; | ||
} | ||
} else { | ||
httpsModule = 'https'; | ||
} | ||
// Setup a web server | ||
var app = connect(); | ||
// Setup a web server | ||
var app = connect(); | ||
// Add logger. Level 2 logs only errors | ||
if (LiveServer.logLevel === 2) { | ||
app.use(logger('dev', { | ||
skip: function (req, res) { return res.statusCode < 400; } | ||
})); | ||
// Level 2 or above logs all requests | ||
} else if (LiveServer.logLevel > 2) { | ||
app.use(logger('dev')); | ||
} | ||
if (options.spa) { | ||
middleware.push("spa"); | ||
} | ||
// Add middleware | ||
middleware.map(function(mw) { | ||
if (typeof mw === "string") { | ||
var ext = path.extname(mw).toLocaleLowerCase(); | ||
if (ext !== ".js") { | ||
mw = require(path.join(__dirname, "middleware", mw + ".js")); | ||
} else { | ||
mw = require(mw); | ||
} | ||
} | ||
app.use(mw); | ||
}); | ||
// Add logger. Level 2 logs only errors | ||
if (LiveServer.logLevel === 2) { | ||
app.use( | ||
logger('dev', { | ||
skip: function(req, res) { | ||
return res.statusCode < 400; | ||
}, | ||
}) | ||
); | ||
// Level 2 or above logs all requests | ||
} else if (LiveServer.logLevel > 2) { | ||
app.use(logger('dev')); | ||
} | ||
if (options.spa) { | ||
middleware.push('spa'); | ||
} | ||
// Add middleware | ||
middleware.map(function(mw) { | ||
if (typeof mw === 'string') { | ||
var ext = path.extname(mw).toLocaleLowerCase(); | ||
if (ext !== '.js') { | ||
mw = require(path.join(__dirname, 'middleware', mw + '.js')); | ||
} else { | ||
mw = require(mw); | ||
} | ||
} | ||
app.use(mw); | ||
}); | ||
// Use http-auth if configured | ||
if (htpasswd !== null) { | ||
var auth = require('http-auth'); | ||
var basic = auth.basic({ | ||
realm: "Please authorize", | ||
file: htpasswd | ||
}); | ||
app.use(auth.connect(basic)); | ||
} | ||
if (cors) { | ||
app.use(require("cors")({ | ||
origin: true, // reflecting request origin | ||
credentials: true // allowing requests with credentials | ||
})); | ||
} | ||
mount.forEach(function(mountRule) { | ||
var mountPath = path.resolve(process.cwd(), mountRule[1]); | ||
if (!options.watch) // Auto add mount paths to wathing but only if exclusive path option is not given | ||
watchPaths.push(mountPath); | ||
app.use(mountRule[0], staticServer(mountPath)); | ||
if (LiveServer.logLevel >= 1) | ||
console.log('Mapping %s to "%s"', mountRule[0], mountPath); | ||
}); | ||
proxy.forEach(function(proxyRule) { | ||
var proxyOpts = url.parse(proxyRule[1]); | ||
proxyOpts.via = true; | ||
proxyOpts.preserveHost = true; | ||
app.use(proxyRule[0], require('proxy-middleware')(proxyOpts)); | ||
if (LiveServer.logLevel >= 1) | ||
console.log('Mapping %s to "%s"', proxyRule[0], proxyRule[1]); | ||
}); | ||
app.use(staticServerHandler) // Custom static server | ||
.use(entryPoint(staticServerHandler, file)) | ||
.use(serveIndex(root, { icons: true })); | ||
// Use http-auth if configured | ||
if (htpasswd !== null) { | ||
var auth = require('http-auth'); | ||
var basic = auth.basic({ | ||
realm: 'Please authorize', | ||
file: htpasswd, | ||
}); | ||
app.use(auth.connect(basic)); | ||
} | ||
if (cors) { | ||
app.use( | ||
require('cors')({ | ||
origin: true, // reflecting request origin | ||
credentials: true, // allowing requests with credentials | ||
}) | ||
); | ||
} | ||
mount.forEach(function(mountRule) { | ||
var mountPath = path.resolve(process.cwd(), mountRule[1]); | ||
if (!options.watch) | ||
// Auto add mount paths to wathing but only if exclusive path option is not given | ||
watchPaths.push(mountPath); | ||
app.use(mountRule[0], staticServer(mountPath)); | ||
if (LiveServer.logLevel >= 1) | ||
console.log('Mapping %s to "%s"', mountRule[0], mountPath); | ||
}); | ||
proxy.forEach(function(proxyRule) { | ||
var proxyOpts = url.parse(proxyRule[1]); | ||
proxyOpts.via = true; | ||
proxyOpts.preserveHost = true; | ||
app.use(proxyRule[0], require('proxy-middleware')(proxyOpts)); | ||
if (LiveServer.logLevel >= 1) | ||
console.log('Mapping %s to "%s"', proxyRule[0], proxyRule[1]); | ||
}); | ||
app | ||
.use(staticServerHandler) // Custom static server | ||
.use(entryPoint(staticServerHandler, file)) | ||
.use(serveIndex(root, { icons: true })); | ||
var server, protocol; | ||
if (https !== null) { | ||
var httpsConfig = https; | ||
if (typeof https === "string") { | ||
httpsConfig = require(path.resolve(process.cwd(), https)); | ||
} | ||
server = require(httpsModule).createServer(httpsConfig, app); | ||
protocol = "https"; | ||
} else { | ||
server = http.createServer(app); | ||
protocol = "http"; | ||
} | ||
var server, protocol; | ||
if (https !== null) { | ||
var httpsConfig = https; | ||
if (typeof https === 'string') { | ||
httpsConfig = require(path.resolve(process.cwd(), https)); | ||
} | ||
server = require(httpsModule).createServer(httpsConfig, app); | ||
protocol = 'https'; | ||
} else { | ||
server = http.createServer(app); | ||
protocol = 'http'; | ||
} | ||
// Handle server startup errors | ||
server.addListener('error', function(e) { | ||
if (e.code === 'EADDRINUSE') { | ||
var serveURL = protocol + '://' + host + ':' + port; | ||
console.log('%s is already in use. Trying another port.'.yellow, serveURL); | ||
setTimeout(function() { | ||
server.listen(0, host); | ||
}, 1000); | ||
} else { | ||
console.error(e.toString().red); | ||
LiveServer.shutdown(); | ||
} | ||
}); | ||
// Handle server startup errors | ||
server.addListener('error', function(e) { | ||
if (e.code === 'EADDRINUSE') { | ||
var serveURL = protocol + '://' + host + ':' + port; | ||
console.log( | ||
'%s is already in use. Trying another port.'.yellow, | ||
serveURL | ||
); | ||
setTimeout(function() { | ||
server.listen(0, host); | ||
}, 1000); | ||
} else { | ||
console.error(e.toString().red); | ||
LiveServer.shutdown(); | ||
} | ||
}); | ||
// Handle successful server | ||
server.addListener('listening', function(/*e*/) { | ||
LiveServer.server = server; | ||
// Handle successful server | ||
server.addListener('listening', function(/*e*/) { | ||
LiveServer.server = server; | ||
var address = server.address(); | ||
var serveHost = address.address === "0.0.0.0" ? "127.0.0.1" : address.address; | ||
var openHost = host === "0.0.0.0" ? "127.0.0.1" : host; | ||
var address = server.address(); | ||
var serveHost = | ||
address.address === '0.0.0.0' ? '127.0.0.1' : address.address; | ||
var openHost = host === '0.0.0.0' ? '127.0.0.1' : host; | ||
var serveURL = protocol + '://' + serveHost + ':' + address.port; | ||
var openURL = protocol + '://' + openHost + ':' + address.port; | ||
var serveURL = protocol + '://' + serveHost + ':' + address.port; | ||
var openURL = protocol + '://' + openHost + ':' + address.port; | ||
var serveURLs = [ serveURL ]; | ||
if (LiveServer.logLevel > 2 && address.address === "0.0.0.0") { | ||
var ifaces = os.networkInterfaces(); | ||
serveURLs = Object.keys(ifaces) | ||
.map(function(iface) { | ||
return ifaces[iface]; | ||
}) | ||
// flatten address data, use only IPv4 | ||
.reduce(function(data, addresses) { | ||
addresses.filter(function(addr) { | ||
return addr.family === "IPv4"; | ||
}).forEach(function(addr) { | ||
data.push(addr); | ||
}); | ||
return data; | ||
}, []) | ||
.map(function(addr) { | ||
return protocol + "://" + addr.address + ":" + address.port; | ||
}); | ||
} | ||
var serveURLs = [serveURL]; | ||
if (LiveServer.logLevel > 2 && address.address === '0.0.0.0') { | ||
var ifaces = os.networkInterfaces(); | ||
serveURLs = Object.keys(ifaces) | ||
.map(function(iface) { | ||
return ifaces[iface]; | ||
}) | ||
// flatten address data, use only IPv4 | ||
.reduce(function(data, addresses) { | ||
addresses | ||
.filter(function(addr) { | ||
return addr.family === 'IPv4'; | ||
}) | ||
.forEach(function(addr) { | ||
data.push(addr); | ||
}); | ||
return data; | ||
}, []) | ||
.map(function(addr) { | ||
return protocol + '://' + addr.address + ':' + address.port; | ||
}); | ||
} | ||
// Output | ||
if (LiveServer.logLevel >= 1) { | ||
if (serveURL === openURL) | ||
if (serveURLs.length === 1) { | ||
console.log(("Serving \"%s\" at %s").green, root, serveURLs[0]); | ||
} else { | ||
console.log(("Serving \"%s\" at\n\t%s").green, root, serveURLs.join("\n\t")); | ||
} | ||
else | ||
console.log(("Serving \"%s\" at %s (%s)").green, root, openURL, serveURL); | ||
} | ||
// Output | ||
if (LiveServer.logLevel >= 1) { | ||
if (serveURL === openURL) | ||
if (serveURLs.length === 1) { | ||
console.log('Serving "%s" at %s'.green, root, serveURLs[0]); | ||
} else { | ||
console.log( | ||
'Serving "%s" at\n\t%s'.green, | ||
root, | ||
serveURLs.join('\n\t') | ||
); | ||
} | ||
else | ||
console.log('Serving "%s" at %s (%s)'.green, root, openURL, serveURL); | ||
} | ||
// Launch browser | ||
if (openPath !== null) | ||
if (typeof openPath === "object") { | ||
openPath.forEach(function(p) { | ||
open(openURL + p, {app: browser}); | ||
}); | ||
} else { | ||
open(openURL + openPath, {app: browser}); | ||
} | ||
}); | ||
// Launch browser | ||
if (openPath !== null) | ||
if (typeof openPath === 'object') { | ||
openPath.forEach(function(p) { | ||
open(openURL + p, { app: browser }); | ||
}); | ||
} else { | ||
open(openURL + openPath, { app: browser }); | ||
} | ||
}); | ||
// Setup server to listen at port | ||
server.listen(port, host); | ||
// Setup server to listen at port | ||
server.listen(port, host); | ||
// WebSocket | ||
var clients = []; | ||
server.addListener('upgrade', function(request, socket, head) { | ||
var ws = new WebSocket(request, socket, head); | ||
ws.onopen = function() { ws.send('connected'); }; | ||
// WebSocket | ||
var clients = []; | ||
server.addListener('upgrade', function(request, socket, head) { | ||
var ws = new WebSocket(request, socket, head); | ||
ws.onopen = function() { | ||
ws.send('connected'); | ||
}; | ||
if (wait > 0) { | ||
(function() { | ||
var wssend = ws.send; | ||
var waitTimeout; | ||
ws.send = function() { | ||
var args = arguments; | ||
if (waitTimeout) clearTimeout(waitTimeout); | ||
waitTimeout = setTimeout(function(){ | ||
wssend.apply(ws, args); | ||
}, wait); | ||
}; | ||
})(); | ||
} | ||
if (wait > 0) { | ||
(function() { | ||
var wssend = ws.send; | ||
var waitTimeout; | ||
ws.send = function() { | ||
var args = arguments; | ||
if (waitTimeout) clearTimeout(waitTimeout); | ||
waitTimeout = setTimeout(function() { | ||
wssend.apply(ws, args); | ||
}, wait); | ||
}; | ||
})(); | ||
} | ||
ws.onclose = function() { | ||
clients = clients.filter(function (x) { | ||
return x !== ws; | ||
}); | ||
}; | ||
ws.onclose = function() { | ||
clients = clients.filter(function(x) { | ||
return x !== ws; | ||
}); | ||
}; | ||
clients.push(ws); | ||
}); | ||
clients.push(ws); | ||
}); | ||
var ignored = [ | ||
function(testPath) { // Always ignore dotfiles (important e.g. because editor hidden temp files) | ||
return testPath !== "." && /(^[.#]|(?:__|~)$)/.test(path.basename(testPath)); | ||
} | ||
]; | ||
if (options.ignore) { | ||
ignored = ignored.concat(options.ignore); | ||
} | ||
if (options.ignorePattern) { | ||
ignored.push(options.ignorePattern); | ||
} | ||
// Setup file watcher | ||
LiveServer.watcher = chokidar.watch(watchPaths, { | ||
ignored: ignored, | ||
ignoreInitial: true | ||
}); | ||
function handleChange(changePath) { | ||
var cssChange = path.extname(changePath) === ".css" && !noCssInject; | ||
if (LiveServer.logLevel >= 1) { | ||
if (cssChange) | ||
console.log("CSS change detected".magenta, changePath); | ||
else console.log("Change detected".cyan, changePath); | ||
} | ||
clients.forEach(function(ws) { | ||
if (ws) | ||
ws.send(cssChange ? 'refreshcss' : 'reload'); | ||
}); | ||
} | ||
LiveServer.watcher | ||
.on("change", handleChange) | ||
.on("add", handleChange) | ||
.on("unlink", handleChange) | ||
.on("addDir", handleChange) | ||
.on("unlinkDir", handleChange) | ||
.on("ready", function () { | ||
if (LiveServer.logLevel >= 1) | ||
console.log("Ready for changes".cyan); | ||
}) | ||
.on("error", function (err) { | ||
console.log("ERROR:".red, err); | ||
}); | ||
LiveServer.refreshCSS = function () { | ||
if (clients.length) { | ||
clients.forEach(function(ws) { | ||
if (ws) { | ||
ws.send('refreshcss'); | ||
} | ||
}); | ||
} | ||
}; | ||
LiveServer.reload = function () { | ||
if (clients.length) { | ||
clients.forEach(function (ws) { | ||
if (ws) { | ||
ws.send('reload'); | ||
} | ||
}); | ||
} | ||
}; | ||
return server; | ||
var ignored = [ | ||
function(testPath) { | ||
// Always ignore dotfiles (important e.g. because editor hidden temp files) | ||
return ( | ||
testPath !== '.' && /(^[.#]|(?:__|~)$)/.test(path.basename(testPath)) | ||
); | ||
}, | ||
]; | ||
if (options.ignore) { | ||
ignored = ignored.concat(options.ignore); | ||
} | ||
if (options.ignorePattern) { | ||
ignored.push(options.ignorePattern); | ||
} | ||
// Setup file watcher | ||
LiveServer.watcher = chokidar.watch(watchPaths, { | ||
ignored: ignored, | ||
ignoreInitial: true, | ||
}); | ||
function handleChange(changePath) { | ||
var cssChange = path.extname(changePath) === '.css' && !noCssInject; | ||
if (LiveServer.logLevel >= 1) { | ||
if (cssChange) console.log('CSS change detected'.magenta, changePath); | ||
else console.log('Change detected'.cyan, changePath); | ||
} | ||
clients.forEach(function(ws) { | ||
if (ws) ws.send(cssChange ? 'refreshcss' : 'reload'); | ||
}); | ||
} | ||
LiveServer.watcher | ||
.on('change', handleChange) | ||
.on('add', handleChange) | ||
.on('unlink', handleChange) | ||
.on('addDir', handleChange) | ||
.on('unlinkDir', handleChange) | ||
.on('ready', function() { | ||
if (LiveServer.logLevel >= 1) console.log('Ready for changes'.cyan); | ||
}) | ||
.on('error', function(err) { | ||
console.log('ERROR:'.red, err); | ||
}); | ||
LiveServer.refreshCSS = function() { | ||
if (clients.length) { | ||
clients.forEach(function(ws) { | ||
if (ws) { | ||
ws.send('refreshcss'); | ||
} | ||
}); | ||
} | ||
}; | ||
LiveServer.reload = function() { | ||
if (clients.length) { | ||
clients.forEach(function(ws) { | ||
if (ws) { | ||
ws.send('reload'); | ||
} | ||
}); | ||
} | ||
}; | ||
return server; | ||
}; | ||
LiveServer.shutdown = function() { | ||
var watcher = LiveServer.watcher; | ||
if (watcher) { | ||
watcher.close(); | ||
} | ||
var server = LiveServer.server; | ||
if (server) | ||
server.close(); | ||
var watcher = LiveServer.watcher; | ||
if (watcher) { | ||
watcher.close(); | ||
} | ||
var server = LiveServer.server; | ||
if (server) server.close(); | ||
}; | ||
module.exports = LiveServer; |
@@ -5,171 +5,151 @@ #!/usr/bin/env node | ||
var assign = require('object-assign'); | ||
var liveServer = require("./index"); | ||
var liveServer = require('./index'); | ||
var opts = { | ||
host: process.env.IP, | ||
port: process.env.PORT, | ||
open: true, | ||
mount: [], | ||
proxy: [], | ||
middleware: [], | ||
logLevel: 2, | ||
host: process.env.IP, | ||
port: process.env.PORT, | ||
open: true, | ||
mount: [], | ||
proxy: [], | ||
middleware: [], | ||
logLevel: 2, | ||
}; | ||
var homeDir = process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME']; | ||
var homeDir = | ||
process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME']; | ||
var configPath = path.join(homeDir, '.live-server.json'); | ||
if (fs.existsSync(configPath)) { | ||
var userConfig = fs.readFileSync(configPath, 'utf8'); | ||
assign(opts, JSON.parse(userConfig)); | ||
if (opts.ignorePattern) opts.ignorePattern = new RegExp(opts.ignorePattern); | ||
var userConfig = fs.readFileSync(configPath, 'utf8'); | ||
assign(opts, JSON.parse(userConfig)); | ||
if (opts.ignorePattern) opts.ignorePattern = new RegExp(opts.ignorePattern); | ||
} | ||
for (var i = process.argv.length - 1; i >= 2; --i) { | ||
var arg = process.argv[i]; | ||
if (arg.indexOf("--port=") > -1) { | ||
var portString = arg.substring(7); | ||
var portNumber = parseInt(portString, 10); | ||
if (portNumber === +portString) { | ||
opts.port = portNumber; | ||
process.argv.splice(i, 1); | ||
} | ||
} | ||
else if (arg.indexOf("--host=") > -1) { | ||
opts.host = arg.substring(7); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--open=") > -1) { | ||
var open = arg.substring(7); | ||
if (open.indexOf('/') !== 0) { | ||
open = '/' + open; | ||
} | ||
switch (typeof opts.open) { | ||
case "boolean": | ||
opts.open = open; | ||
break; | ||
case "string": | ||
opts.open = [opts.open, open]; | ||
break; | ||
case "object": | ||
opts.open.push(open); | ||
break; | ||
} | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--watch=") > -1) { | ||
// Will be modified later when cwd is known | ||
opts.watch = arg.substring(8).split(","); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--ignore=") > -1) { | ||
// Will be modified later when cwd is known | ||
opts.ignore = arg.substring(9).split(","); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--ignorePattern=") > -1) { | ||
opts.ignorePattern = new RegExp(arg.substring(16)); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg === "--no-css-inject") { | ||
opts.noCssInject = true; | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg === "--no-browser") { | ||
opts.open = false; | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--browser=") > -1) { | ||
opts.browser = arg.substring(10).split(","); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--entry-file=") > -1) { | ||
var file = arg.substring(13); | ||
if (file.length) { | ||
opts.file = file; | ||
process.argv.splice(i, 1); | ||
} | ||
} | ||
else if (arg === "--spa") { | ||
opts.middleware.push("spa"); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg === "--quiet" || arg === "-q") { | ||
opts.logLevel = 0; | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg === "--verbose" || arg === "-V") { | ||
opts.logLevel = 3; | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--mount=") > -1) { | ||
// e.g. "--mount=/components:./node_modules" will be ['/components', '<process.cwd()>/node_modules'] | ||
// split only on the first ":", as the path may contain ":" as well (e.g. C:\file.txt) | ||
var match = arg.substring(8).match(/([^:]+):(.+)$/); | ||
match[2] = path.resolve(process.cwd(), match[2]); | ||
opts.mount.push([ match[1], match[2] ]); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--wait=") > -1) { | ||
var waitString = arg.substring(7); | ||
var waitNumber = parseInt(waitString, 10); | ||
if (waitNumber === +waitString) { | ||
opts.wait = waitNumber; | ||
process.argv.splice(i, 1); | ||
} | ||
} | ||
else if (arg === "--version" || arg === "-v") { | ||
var packageJson = require('./package.json'); | ||
console.log(packageJson.name, packageJson.version); | ||
process.exit(); | ||
} | ||
else if (arg.indexOf("--htpasswd=") > -1) { | ||
opts.htpasswd = arg.substring(11); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg === "--cors") { | ||
opts.cors = true; | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--https=") > -1) { | ||
opts.https = arg.substring(8); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--https-module=") > -1) { | ||
opts.httpsModule = arg.substring(15); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--proxy=") > -1) { | ||
// split only on the first ":", as the URL will contain ":" as well | ||
var match = arg.substring(8).match(/([^:]+):(.+)$/); | ||
opts.proxy.push([ match[1], match[2] ]); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg.indexOf("--middleware=") > -1) { | ||
opts.middleware.push(arg.substring(13)); | ||
process.argv.splice(i, 1); | ||
} | ||
else if (arg === "--help" || arg === "-h") { | ||
console.log('Usage: live-server [-v|--version] [-h|--help] [-q|--quiet] [--port=PORT] [--host=HOST] [--open=PATH] [--no-browser] [--browser=BROWSER] [--ignore=PATH] [--ignorePattern=RGXP] [--no-css-inject] [--entry-file=PATH] [--spa] [--mount=ROUTE:PATH] [--wait=MILLISECONDS] [--htpasswd=PATH] [--cors] [--https=PATH] [--https-module=MODULE_NAME] [--proxy=PATH] [PATH]'); | ||
process.exit(); | ||
} | ||
else if (arg === "--test") { | ||
// Hidden param for tests to exit automatically | ||
setTimeout(liveServer.shutdown, 500); | ||
process.argv.splice(i, 1); | ||
} | ||
var arg = process.argv[i]; | ||
if (arg.indexOf('--port=') > -1) { | ||
var portString = arg.substring(7); | ||
var portNumber = parseInt(portString, 10); | ||
if (portNumber === +portString) { | ||
opts.port = portNumber; | ||
process.argv.splice(i, 1); | ||
} | ||
} else if (arg.indexOf('--host=') > -1) { | ||
opts.host = arg.substring(7); | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--open=') > -1) { | ||
var open = arg.substring(7); | ||
if (open.indexOf('/') !== 0) { | ||
open = '/' + open; | ||
} | ||
switch (typeof opts.open) { | ||
case 'boolean': | ||
opts.open = open; | ||
break; | ||
case 'string': | ||
opts.open = [opts.open, open]; | ||
break; | ||
case 'object': | ||
opts.open.push(open); | ||
break; | ||
} | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--watch=') > -1) { | ||
// Will be modified later when cwd is known | ||
opts.watch = arg.substring(8).split(','); | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--ignore=') > -1) { | ||
// Will be modified later when cwd is known | ||
opts.ignore = arg.substring(9).split(','); | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--ignorePattern=') > -1) { | ||
opts.ignorePattern = new RegExp(arg.substring(16)); | ||
process.argv.splice(i, 1); | ||
} else if (arg === '--no-css-inject') { | ||
opts.noCssInject = true; | ||
process.argv.splice(i, 1); | ||
} else if (arg === '--no-browser') { | ||
opts.open = false; | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--browser=') > -1) { | ||
opts.browser = arg.substring(10).split(','); | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--entry-file=') > -1) { | ||
var file = arg.substring(13); | ||
if (file.length) { | ||
opts.file = file; | ||
process.argv.splice(i, 1); | ||
} | ||
} else if (arg === '--spa') { | ||
opts.middleware.push('spa'); | ||
process.argv.splice(i, 1); | ||
} else if (arg === '--quiet' || arg === '-q') { | ||
opts.logLevel = 0; | ||
process.argv.splice(i, 1); | ||
} else if (arg === '--verbose' || arg === '-V') { | ||
opts.logLevel = 3; | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--mount=') > -1) { | ||
// e.g. "--mount=/components:./node_modules" will be ['/components', '<process.cwd()>/node_modules'] | ||
// split only on the first ":", as the path may contain ":" as well (e.g. C:\file.txt) | ||
var match = arg.substring(8).match(/([^:]+):(.+)$/); | ||
match[2] = path.resolve(process.cwd(), match[2]); | ||
opts.mount.push([match[1], match[2]]); | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--wait=') > -1) { | ||
var waitString = arg.substring(7); | ||
var waitNumber = parseInt(waitString, 10); | ||
if (waitNumber === +waitString) { | ||
opts.wait = waitNumber; | ||
process.argv.splice(i, 1); | ||
} | ||
} else if (arg === '--version' || arg === '-v') { | ||
var packageJson = require('./package.json'); | ||
console.log(packageJson.name, packageJson.version); | ||
process.exit(); | ||
} else if (arg.indexOf('--htpasswd=') > -1) { | ||
opts.htpasswd = arg.substring(11); | ||
process.argv.splice(i, 1); | ||
} else if (arg === '--cors') { | ||
opts.cors = true; | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--https=') > -1) { | ||
opts.https = arg.substring(8); | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--https-module=') > -1) { | ||
opts.httpsModule = arg.substring(15); | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--proxy=') > -1) { | ||
// split only on the first ":", as the URL will contain ":" as well | ||
var match = arg.substring(8).match(/([^:]+):(.+)$/); | ||
opts.proxy.push([match[1], match[2]]); | ||
process.argv.splice(i, 1); | ||
} else if (arg.indexOf('--middleware=') > -1) { | ||
opts.middleware.push(arg.substring(13)); | ||
process.argv.splice(i, 1); | ||
} else if (arg === '--help' || arg === '-h') { | ||
console.log( | ||
'Usage: live-server [-v|--version] [-h|--help] [-q|--quiet] [--port=PORT] [--host=HOST] [--open=PATH] [--no-browser] [--browser=BROWSER] [--ignore=PATH] [--ignorePattern=RGXP] [--no-css-inject] [--entry-file=PATH] [--spa] [--mount=ROUTE:PATH] [--wait=MILLISECONDS] [--htpasswd=PATH] [--cors] [--https=PATH] [--https-module=MODULE_NAME] [--proxy=PATH] [PATH]' | ||
); | ||
process.exit(); | ||
} else if (arg === '--test') { | ||
// Hidden param for tests to exit automatically | ||
setTimeout(liveServer.shutdown, 500); | ||
process.argv.splice(i, 1); | ||
} | ||
} | ||
// Patch paths | ||
var dir = opts.root = process.argv[2] || ""; | ||
var dir = (opts.root = process.argv[2] || ''); | ||
if (opts.watch) { | ||
opts.watch = opts.watch.map(function(relativePath) { | ||
return path.join(dir, relativePath); | ||
}); | ||
opts.watch = opts.watch.map(function(relativePath) { | ||
return path.join(dir, relativePath); | ||
}); | ||
} | ||
if (opts.ignore) { | ||
opts.ignore = opts.ignore.map(function(relativePath) { | ||
return path.join(dir, relativePath); | ||
}); | ||
opts.ignore = opts.ignore.map(function(relativePath) { | ||
return path.join(dir, relativePath); | ||
}); | ||
} | ||
liveServer.start(opts); |
module.exports = function(req, res, next) { | ||
res.statusCode = 202; | ||
next(); | ||
} | ||
res.statusCode = 202; | ||
next(); | ||
}; |
// Single Page Apps - redirect to /#/ except when a file extension is given | ||
var path = require('path'); | ||
module.exports = function(req, res, next) { | ||
if (req.method !== "GET" && req.method !== "HEAD") | ||
next(); | ||
if (req.url !== '/' && path.extname(req.url) === '') { | ||
var route = req.url; | ||
req.url = '/'; | ||
res.statusCode = 302; | ||
res.setHeader('Location', req.url + '#' + route); | ||
res.end(); | ||
} | ||
else next(); | ||
} | ||
if (req.method !== 'GET' && req.method !== 'HEAD') next(); | ||
if (req.url !== '/' && path.extname(req.url) === '') { | ||
var route = req.url; | ||
req.url = '/'; | ||
res.statusCode = 302; | ||
res.setHeader('Location', req.url + '#' + route); | ||
res.end(); | ||
} else next(); | ||
}; |
// Single Page Apps - redirect to /#/ | ||
module.exports = function(req, res, next) { | ||
if (req.method !== "GET" && req.method !== "HEAD") | ||
next(); | ||
if (req.url !== '/') { | ||
var route = req.url; | ||
req.url = '/'; | ||
res.statusCode = 302; | ||
res.setHeader('Location', req.url + '#' + route); | ||
res.end(); | ||
} | ||
else next(); | ||
} | ||
if (req.method !== 'GET' && req.method !== 'HEAD') next(); | ||
if (req.url !== '/') { | ||
var route = req.url; | ||
req.url = '/'; | ||
res.statusCode = 302; | ||
res.setHeader('Location', req.url + '#' + route); | ||
res.end(); | ||
} else next(); | ||
}; |
{ | ||
"name": "@pattern-lab/live-server", | ||
"version": "1.3.3-alpha.1", | ||
"version": "1.3.3-alpha.2", | ||
"description": "simple development http server with live reload capability", | ||
@@ -30,3 +30,3 @@ "keywords": [ | ||
"devDependencies": { | ||
"eslint": "^4.9.0", | ||
"eslint": "4.18.2", | ||
"jshint": "^2.9.2", | ||
@@ -33,0 +33,0 @@ "mocha": "^4.0.1", |
269
README.md
@@ -1,268 +0,1 @@ | ||
[](https://www.npmjs.org/package/live-server) | ||
[](https://www.npmjs.org/package/live-server) | ||
[](https://travis-ci.org/tapio/live-server) | ||
Live Server | ||
=========== | ||
This is a little development server with live reload capability. Use it for hacking your HTML/JavaScript/CSS files, but not for deploying the final site. | ||
There are two reasons for using this: | ||
1. AJAX requests don't work with the `file://` protocol due to security restrictions, i.e. you need a server if your site fetches content through JavaScript. | ||
2. Having the page reload automatically after changes to files can accelerate development. | ||
You don't need to install any browser plugins or manually add code snippets to your pages for the reload functionality to work, see "How it works" section below for more information. If you don't want/need the live reload, you should probably use something even simpler, like the following Python-based one-liner: | ||
python -m SimpleHTTPServer | ||
Installation | ||
------------ | ||
You need node.js and npm. You should probably install this globally. | ||
**Npm way** | ||
npm install -g live-server | ||
**Manual way** | ||
git clone https://github.com/tapio/live-server | ||
cd live-server | ||
npm install # Local dependencies if you want to hack | ||
npm install -g # Install globally | ||
Usage from command line | ||
----------------------- | ||
Issue the command `live-server` in your project's directory. Alternatively you can add the path to serve as a command line parameter. | ||
This will automatically launch the default browser. When you make a change to any file, the browser will reload the page - unless it was a CSS file in which case the changes are applied without a reload. | ||
Command line parameters: | ||
* `--port=NUMBER` - select port to use, default: PORT env var or 8080 | ||
* `--host=ADDRESS` - select host address to bind to, default: IP env var or 0.0.0.0 ("any address") | ||
* `--no-browser` - suppress automatic web browser launching | ||
* `--browser=BROWSER` - specify browser to use instead of system default | ||
* `--quiet | -q` - suppress logging | ||
* `--verbose | -V` - more logging (logs all requests, shows all listening IPv4 interfaces, etc.) | ||
* `--open=PATH` - launch browser to PATH instead of server root | ||
* `--watch=PATH` - comma-separated string of paths to exclusively watch for changes (default: watch everything) | ||
* `--ignore=PATH` - comma-separated string of paths to ignore ([anymatch](https://github.com/es128/anymatch)-compatible definition) | ||
* `--ignorePattern=RGXP` - Regular expression of files to ignore (ie `.*\.jade`) (**DEPRECATED** in favor of `--ignore`) | ||
* `--no-css-inject` - reload page on CSS change, rather than injecting changed CSS | ||
* `--middleware=PATH` - path to .js file exporting a middleware function to add; can be a name without path nor extension to reference bundled middlewares in `middleware` folder | ||
* `--entry-file=PATH` - serve this file (server root relative) in place of missing files (useful for single page apps) | ||
* `--mount=ROUTE:PATH` - serve the paths contents under the defined route (multiple definitions possible) | ||
* `--spa` - translate requests from /abc to /#/abc (handy for Single Page Apps) | ||
* `--wait=MILLISECONDS` - (default 100ms) wait for all changes, before reloading | ||
* `--htpasswd=PATH` - Enables http-auth expecting htpasswd file located at PATH | ||
* `--cors` - Enables CORS for any origin (reflects request origin, requests with credentials are supported) | ||
* `--https=PATH` - PATH to a HTTPS configuration module | ||
* `--https-module=MODULE_NAME` - Custom HTTPS module (e.g. `spdy`) | ||
* `--proxy=ROUTE:URL` - proxy all requests for ROUTE to URL | ||
* `--help | -h` - display terse usage hint and exit | ||
* `--version | -v` - display version and exit | ||
Default options: | ||
If a file `~/.live-server.json` exists it will be loaded and used as default options for live-server on the command line. See "Usage from node" for option names. | ||
Usage from node | ||
--------------- | ||
```javascript | ||
var liveServer = require("live-server"); | ||
var params = { | ||
port: 8181, // Set the server port. Defaults to 8080. | ||
host: "0.0.0.0", // Set the address to bind to. Defaults to 0.0.0.0 or process.env.IP. | ||
root: "/public", // Set root directory that's being served. Defaults to cwd. | ||
open: false, // When false, it won't load your browser by default. | ||
ignore: 'scss,my/templates', // comma-separated string for paths to ignore | ||
file: "index.html", // When set, serve this file for every 404 (useful for single-page applications) | ||
wait: 1000, // Waits for all changes, before reloading. Defaults to 0 sec. | ||
mount: [['/components', './node_modules']], // Mount a directory to a route. | ||
logLevel: 2, // 0 = errors only, 1 = some, 2 = lots | ||
middleware: [function(req, res, next) { next(); }] // Takes an array of Connect-compatible middleware that are injected into the server middleware stack | ||
}; | ||
liveServer.start(params); | ||
``` | ||
HTTPS | ||
--------------- | ||
In order to enable HTTPS support, you'll need to create a configuration module. | ||
The module must export an object that will be used to configure a HTTPS server. | ||
The keys are the same as the keys in `options` for [tls.createServer](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener). | ||
For example: | ||
```javascript | ||
var fs = require("fs"); | ||
module.exports = { | ||
cert: fs.readFileSync(__dirname + "/server.cert"), | ||
key: fs.readFileSync(__dirname + "/server.key"), | ||
passphrase: "12345" | ||
}; | ||
``` | ||
If using the node API, you can also directly pass a configuration object instead of a path to the module. | ||
HTTP/2 | ||
--------------- | ||
To get HTTP/2 support one can provide a custom HTTPS module via `--https-module` CLI parameter (`httpsModule` option for Node.js script). **Be sure to install the module first.** | ||
HTTP/2 unencrypted mode is not supported by browsers, thus not supported by `live-server`. See [this question](https://http2.github.io/faq/#does-http2-require-encryption) and [can I use page on HTTP/2](http://caniuse.com/#search=http2) for more details. | ||
For example from CLI(bash): | ||
live-server \ | ||
--https=path/to/https.conf.js \ | ||
--https-module=spdy \ | ||
my-app-folder/ | ||
Troubleshooting | ||
--------------- | ||
* No reload on changes | ||
* Open your browser's console: there should be a message at the top stating that live reload is enabled. Note that you will need a browser that supports WebSockets. If there are errors, deal with them. If it's still not working, [file an issue](https://github.com/tapio/live-server/issues). | ||
* Error: watch <PATH> ENOSPC | ||
* See [this suggested solution](http://stackoverflow.com/questions/22475849/node-js-error-enospc/32600959#32600959). | ||
* Reload works but changes are missing or outdated | ||
* Try using `--wait=MS` option. Where `MS` is time in milliseconds to wait before issuing a reload. | ||
How it works | ||
------------ | ||
The server is a simple node app that serves the working directory and its subdirectories. It also watches the files for changes and when that happens, it sends a message through a web socket connection to the browser instructing it to reload. In order for the client side to support this, the server injects a small piece of JavaScript code to each requested html file. This script establishes the web socket connection and listens to the reload requests. CSS files can be refreshed without a full page reload by finding the referenced stylesheets from the DOM and tricking the browser to fetch and parse them again. | ||
Contributing | ||
------------ | ||
We welcome contributions! See [CONTRIBUTING.md](.github/CONTRIBUTING.md) for details. | ||
Version history | ||
--------------- | ||
* v1.2.0 | ||
- Add `--middleware` parameter to use external middlewares | ||
- `middleware` API parameter now also accepts strings similar to `--middleware` | ||
- Changed file watcher to improve speed (@pavel) | ||
- `--ignore` now accepts regexps and globs, `--ignorePattern` deprecated (@pavel) | ||
- Added `--verbose` cli option (logLevel 3) (@pavel) | ||
- Logs all requests, displays warning when can't inject html file, displays all listening IPv4 interfaces... | ||
- HTTPS configuration now also accepts a plain object (@pavel) | ||
- Move `--spa` to a bundled middleware file | ||
- New bundled `spa-no-assets` middleware that works like `spa` but ignores requests with extension | ||
- Allow multiple `--open` arguments (@PirtleShell) | ||
- Inject to `head` if `body` not found (@pmd1991) | ||
- Update dependencies | ||
* v1.1.0 | ||
- Proxy support (@pavel) | ||
- Middleware support (@achandrasekar) | ||
- Dependency updates (@tapio, @rahatarmanahmed) | ||
- Using Travis CI | ||
* v1.0.0 | ||
- HTTPS support (@pavel) | ||
- HTTP Basic authentication support (@hey-johnnypark) | ||
- CORS support (@pavel) | ||
- Support mounting single files (@pavel) | ||
- `--spa` cli option for single page apps, translates requests from /abc to /#/abc (@evanplaice) | ||
- Check `IP` env var for default host (@dotnetCarpenter) | ||
- Fix `ignorePattern` from config file (@cyfersystems) | ||
- Fix test running for Windows (@peterhull90) | ||
* v0.9.2 | ||
- Updated most dependencies to latest versions | ||
- `--quiet` now silences warning about injection failure | ||
- Giving explicit `--watch` paths now disables adding mounted paths to watching | ||
* v0.9.1 | ||
- `--ignorePattern=RGXP` exclude files from watching by regexp (@psi-4ward) | ||
- `--watch=PATH` cli option to only watch given paths | ||
* v0.9.0 | ||
- `--mount=ROUTE:PATH` cli option to specify alternative routes to paths (@pmentz) | ||
- `--browser=BROWSER` cli option to specify browser to use (@sakiv) | ||
- Improved error reporting | ||
- Basic support for injecting the reload code to SVG files (@dotnetCarpenter, @tapio) | ||
- LiveServer.shutdown() function to close down the server and file watchers | ||
- If host parameter is given, use it for browser URL instead of resolved IP | ||
- Initial testing framework (@harrytruong, @evanplaice, @tapio) | ||
* v0.8.2 | ||
- Load initial settings from `~/.live-server.json` if exists (@mikker) | ||
- Allow `--port=0` to select random port (@viqueen) | ||
- Fix injecting when file extension is not lower case (@gusgard) | ||
- Fail gracefully if browser does not support WebSockets (@mattymaloney) | ||
- Switched to a more maintained browser opening library | ||
* v0.8.1 | ||
- Add `--version / -v` command line flags to display version | ||
- Add `--host` cli option to mirror the API parameter | ||
- Once again use 127.0.0.1 instead of 0.0.0.0 as the browser URL | ||
* v0.8.0 | ||
- Support multiple clients simultaneously (@dvv) | ||
- Pick a random available port if the default is in use (@oliverzy, @harrytruong) | ||
- Fix Chrome sometimes not applying CSS changes (@harrytruong) | ||
- `--ignore=PATH` cli option to not watch given server root relative paths (@richardgoater) | ||
- `--entry-file=PATH` cli option to specify file to use when request is not found (@izeau) | ||
- `--wait=MSECS` cli option to wait specified time before reloading (@leolower, @harrytruong) | ||
* v0.7.1 | ||
- Fix hang caused by trying to inject into fragment html files without `</body>` | ||
- `logLevel` parameter in library to control amount of console spam | ||
- `--quiet` cli option to suppress console spam | ||
- `--open=PATH` cli option to launch browser in specified path instead of root (@richardgoater) | ||
- Library's `noBrowser: true` option is deprecated in favor of `open: false` | ||
* v0.7.0 | ||
- API BREAKAGE: LiveServer library now takes parameters in an object | ||
- Add possibility to specify host to the lib | ||
- Only inject to host page when working with web components (e.g. Polymer) (@davej) | ||
- Open browser to 127.0.0.1, as 0.0.0.0 has issues | ||
- `--no-browser` command line flag to suppress browser launch | ||
- `--help` command line flag to display usage | ||
* v0.6.4 | ||
- Allow specifying port from the command line: `live-server --port=3000` (@Pomax) | ||
- Don't inject script as the first thing so that DOCTYPE remains valid (@wmira) | ||
- Be more explicit with listening to all interfaces (@inadarei) | ||
* v0.6.3 | ||
- Fix multiple _cacheOverride parameters polluting css requests | ||
- Don't create global variables in the injected script | ||
* v0.6.2 | ||
- Fix a deprecation warning from `send` | ||
* v0.6.1 | ||
- Republish to fix npm troubles | ||
* v0.6.0 | ||
- Support for using as node library (@dpgraham) | ||
* v0.5.0 | ||
- Watching was broken with new versions of `watchr` > 2.3.3 | ||
- Added some logging to console | ||
* v0.4.0 | ||
- Allow specifying directory to serve from command line | ||
* v0.3.0 | ||
- Directory listings | ||
* v0.2.0 | ||
- On-the-fly CSS refresh (no page reload) | ||
- Refactoring | ||
* v0.1.1 | ||
- Documentation and meta tweaks | ||
* v0.1.0 | ||
- Initial release | ||
License | ||
------- | ||
Uses MIT licensed code from [Connect](https://github.com/senchalabs/connect/) and [Roots](https://github.com/jenius/roots). | ||
(MIT License) | ||
Copyright (c) 2012 Tapio Vierros | ||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
Fork and extension of https://github.com/tapio/live-server |
var request = require('supertest'); | ||
var path = require('path'); | ||
var liveServer = require('..').start({ | ||
root: path.join(__dirname, "data"), | ||
port: 0, | ||
open: false | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
}); | ||
describe('basic functional tests', function(){ | ||
it('should respond with index.html', function(done){ | ||
request(liveServer) | ||
.get('/') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/hello world/i) | ||
.expect(200, done); | ||
}); | ||
it('should have injected script', function(done){ | ||
request(liveServer) | ||
.get('/') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i) | ||
.expect(200, done); | ||
}); | ||
it('should inject script when tags are in CAPS', function(done){ | ||
request(liveServer) | ||
.get('/index-caps.htm') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i) | ||
.expect(200, done); | ||
}); | ||
it('should inject to <head> when no <body>', function(done){ | ||
request(liveServer) | ||
.get('/index-head.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i) | ||
.expect(200, done); | ||
}); | ||
it('should inject also svg files', function(done){ | ||
request(liveServer) | ||
.get('/test.svg') | ||
.expect('Content-Type', 'image/svg+xml') | ||
.expect(function(res) { | ||
if (res.body.toString().indexOf("Live reload enabled") == -1) | ||
throw new Error("injected code not found"); | ||
}) | ||
.expect(200, done); | ||
}); | ||
it('should not inject html fragments', function(done){ | ||
request(liveServer) | ||
.get('/fragment.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(function(res) { | ||
if (res.text.toString().indexOf("Live reload enabled") > -1) | ||
throw new Error("injected code should not be found"); | ||
}) | ||
.expect(200, done); | ||
}); | ||
xit('should have WebSocket connection', function(done){ | ||
done(); // todo | ||
}); | ||
xit('should reload on page change', function(done){ | ||
done(); // todo | ||
}); | ||
xit('should reload (without refreshing) on css change', function(done){ | ||
done(); // todo | ||
}); | ||
describe('basic functional tests', function() { | ||
it('should respond with index.html', function(done) { | ||
request(liveServer) | ||
.get('/') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/hello world/i) | ||
.expect(200, done); | ||
}); | ||
it('should have injected script', function(done) { | ||
request(liveServer) | ||
.get('/') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i) | ||
.expect(200, done); | ||
}); | ||
it('should inject script when tags are in CAPS', function(done) { | ||
request(liveServer) | ||
.get('/index-caps.htm') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i) | ||
.expect(200, done); | ||
}); | ||
it('should inject to <head> when no <body>', function(done) { | ||
request(liveServer) | ||
.get('/index-head.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/<script [^]+?live reload enabled[^]+?<\/script>/i) | ||
.expect(200, done); | ||
}); | ||
it('should inject also svg files', function(done) { | ||
request(liveServer) | ||
.get('/test.svg') | ||
.expect('Content-Type', 'image/svg+xml') | ||
.expect(function(res) { | ||
if (res.body.toString().indexOf('Live reload enabled') == -1) | ||
throw new Error('injected code not found'); | ||
}) | ||
.expect(200, done); | ||
}); | ||
it('should not inject html fragments', function(done) { | ||
request(liveServer) | ||
.get('/fragment.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(function(res) { | ||
if (res.text.toString().indexOf('Live reload enabled') > -1) | ||
throw new Error('injected code should not be found'); | ||
}) | ||
.expect(200, done); | ||
}); | ||
xit('should have WebSocket connection', function(done) { | ||
done(); // todo | ||
}); | ||
xit('should reload on page change', function(done) { | ||
done(); // todo | ||
}); | ||
xit('should reload (without refreshing) on css change', function(done) { | ||
done(); // todo | ||
}); | ||
}); |
130
test/cli.js
var assert = require('assert'); | ||
var path = require('path'); | ||
var exec = require('child_process').execFile; | ||
var cmd = path.join(__dirname, "..", "live-server.js"); | ||
var cmd = path.join(__dirname, '..', 'live-server.js'); | ||
var opts = { | ||
timeout: 2000, | ||
maxBuffer: 1024 | ||
timeout: 2000, | ||
maxBuffer: 1024, | ||
}; | ||
function exec_test(args, callback) { | ||
if (process.platform === 'win32') | ||
exec(process.execPath, [ cmd ].concat(args), opts, callback); | ||
else | ||
exec(cmd, args, opts, callback); | ||
if (process.platform === 'win32') | ||
exec(process.execPath, [cmd].concat(args), opts, callback); | ||
else exec(cmd, args, opts, callback); | ||
} | ||
describe('command line usage', function() { | ||
it('--version', function(done) { | ||
exec_test([ "--version" ], function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout.indexOf("live-server") == 0, "version not found"); | ||
done(); | ||
}); | ||
}); | ||
it('--help', function(done) { | ||
exec_test([ "--help" ], function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout.indexOf("Usage: live-server") == 0, "usage not found"); | ||
done(); | ||
}); | ||
}); | ||
it('--quiet', function(done) { | ||
exec_test([ "--quiet", "--no-browser", "--test" ], function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout === "", "stdout not empty"); | ||
done(); | ||
}); | ||
}); | ||
it('--port', function(done) { | ||
exec_test([ "--port=16123", "--no-browser", "--test" ], function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout.indexOf("Serving") == 0, "serving string not found"); | ||
assert(stdout.indexOf("at http://127.0.0.1:16123") != -1, "port string not found"); | ||
done(); | ||
}); | ||
}); | ||
it('--host', function(done) { | ||
exec_test([ "--host=localhost", "--no-browser", "--test" ], function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout.indexOf("Serving") == 0, "serving string not found"); | ||
assert(stdout.indexOf("at http://localhost:") != -1, "host string not found"); | ||
done(); | ||
}); | ||
}); | ||
it('--htpasswd', function(done) { | ||
exec_test( | ||
[ "--htpasswd=" + path.join(__dirname, "data/htpasswd-test"), | ||
"--no-browser", | ||
"--test" | ||
], function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout.indexOf("Serving") == 0, "serving string not found"); | ||
done(); | ||
}); | ||
}); | ||
it('--version', function(done) { | ||
exec_test(['--version'], function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout.indexOf('live-server') == 0, 'version not found'); | ||
done(); | ||
}); | ||
}); | ||
it('--help', function(done) { | ||
exec_test(['--help'], function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout.indexOf('Usage: live-server') == 0, 'usage not found'); | ||
done(); | ||
}); | ||
}); | ||
it('--quiet', function(done) { | ||
exec_test(['--quiet', '--no-browser', '--test'], function( | ||
error, | ||
stdout, | ||
stdin | ||
) { | ||
assert(!error, error); | ||
assert(stdout === '', 'stdout not empty'); | ||
done(); | ||
}); | ||
}); | ||
it('--port', function(done) { | ||
exec_test(['--port=16123', '--no-browser', '--test'], function( | ||
error, | ||
stdout, | ||
stdin | ||
) { | ||
assert(!error, error); | ||
assert(stdout.indexOf('Serving') == 0, 'serving string not found'); | ||
assert( | ||
stdout.indexOf('at http://127.0.0.1:16123') != -1, | ||
'port string not found' | ||
); | ||
done(); | ||
}); | ||
}); | ||
it('--host', function(done) { | ||
exec_test(['--host=localhost', '--no-browser', '--test'], function( | ||
error, | ||
stdout, | ||
stdin | ||
) { | ||
assert(!error, error); | ||
assert(stdout.indexOf('Serving') == 0, 'serving string not found'); | ||
assert( | ||
stdout.indexOf('at http://localhost:') != -1, | ||
'host string not found' | ||
); | ||
done(); | ||
}); | ||
}); | ||
it('--htpasswd', function(done) { | ||
exec_test( | ||
[ | ||
'--htpasswd=' + path.join(__dirname, 'data/htpasswd-test'), | ||
'--no-browser', | ||
'--test', | ||
], | ||
function(error, stdout, stdin) { | ||
assert(!error, error); | ||
assert(stdout.indexOf('Serving') == 0, 'serving string not found'); | ||
done(); | ||
} | ||
); | ||
}); | ||
}); |
@@ -1,7 +0,7 @@ | ||
var fs = require("fs"); | ||
var fs = require('fs'); | ||
module.exports = { | ||
cert: fs.readFileSync(__dirname + "/server.cert"), | ||
key: fs.readFileSync(__dirname + "/server.key"), | ||
passphrase: "12345" | ||
cert: fs.readFileSync(__dirname + '/server.cert'), | ||
key: fs.readFileSync(__dirname + '/server.key'), | ||
passphrase: '12345', | ||
}; |
var request = require('supertest'); | ||
var path = require('path'); | ||
var liveServer = require('..').start({ | ||
root: path.join(__dirname, "data"), | ||
port: 0, | ||
open: false, | ||
cors: true | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
cors: true, | ||
}); | ||
describe('cors tests', function() { | ||
it('should respond with appropriate header', function(done) { | ||
request(liveServer) | ||
.get('/index.html') | ||
.set('Origin', 'http://example.com') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect('Access-Control-Allow-Origin', 'http://example.com') | ||
.expect(/Hello world/i) | ||
.expect(200, done); | ||
}); | ||
it('should support preflighted requests', function(done) { | ||
request(liveServer) | ||
.options('/index.html') | ||
.set('Origin', 'http://example.com') | ||
.set('Access-Control-Request-Method', 'POST') | ||
.set('Access-Control-Request-Headers', 'X-PINGOTHER') | ||
.expect('Access-Control-Allow-Origin', 'http://example.com') | ||
.expect('Access-Control-Allow-Methods', /POST/) | ||
.expect('Access-Control-Allow-Headers', 'X-PINGOTHER') | ||
.expect(204, done); | ||
}); | ||
it('should support requests with credentials', function(done) { | ||
request(liveServer) | ||
.options('/index.html') | ||
.set('Origin', 'http://example.com') | ||
.set('Cookie', 'foo=bar') | ||
.expect('Access-Control-Allow-Origin', 'http://example.com') | ||
.expect('Access-Control-Allow-Credentials', 'true') | ||
.expect(204, done); | ||
}); | ||
it('should respond with appropriate header', function(done) { | ||
request(liveServer) | ||
.get('/index.html') | ||
.set('Origin', 'http://example.com') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect('Access-Control-Allow-Origin', 'http://example.com') | ||
.expect(/Hello world/i) | ||
.expect(200, done); | ||
}); | ||
it('should support preflighted requests', function(done) { | ||
request(liveServer) | ||
.options('/index.html') | ||
.set('Origin', 'http://example.com') | ||
.set('Access-Control-Request-Method', 'POST') | ||
.set('Access-Control-Request-Headers', 'X-PINGOTHER') | ||
.expect('Access-Control-Allow-Origin', 'http://example.com') | ||
.expect('Access-Control-Allow-Methods', /POST/) | ||
.expect('Access-Control-Allow-Headers', 'X-PINGOTHER') | ||
.expect(204, done); | ||
}); | ||
it('should support requests with credentials', function(done) { | ||
request(liveServer) | ||
.options('/index.html') | ||
.set('Origin', 'http://example.com') | ||
.set('Cookie', 'foo=bar') | ||
.expect('Access-Control-Allow-Origin', 'http://example.com') | ||
.expect('Access-Control-Allow-Credentials', 'true') | ||
.expect(204, done); | ||
}); | ||
}); | ||
module.exports = function(req, res, next) { | ||
res.statusCode = 203; | ||
next(); | ||
} | ||
res.statusCode = 203; | ||
next(); | ||
}; |
var request = require('supertest'); | ||
var path = require('path'); | ||
var liveServer = require('..').start({ | ||
root: path.join(__dirname, "data"), | ||
port: 0, | ||
open: false, | ||
htpasswd: path.join(__dirname, "data", "htpasswd-test") | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
htpasswd: path.join(__dirname, 'data', 'htpasswd-test'), | ||
}); | ||
describe('htpasswd tests', function() { | ||
it('should respond with 401 since no password is given', function(done) { | ||
request(liveServer) | ||
.get('/') | ||
.expect(401, done); | ||
}); | ||
it('should respond with 401 since wrong password is given', function(done) { | ||
request(liveServer) | ||
.get('/') | ||
.auth("test", "not-real-password") | ||
.expect(401, done); | ||
}); | ||
it('should respond with 200 since correct password is given', function(done) { | ||
request(liveServer) | ||
.get('/') | ||
.auth("test", "test") | ||
.expect(200, done); | ||
}); | ||
it('should respond with 401 since no password is given', function(done) { | ||
request(liveServer) | ||
.get('/') | ||
.expect(401, done); | ||
}); | ||
it('should respond with 401 since wrong password is given', function(done) { | ||
request(liveServer) | ||
.get('/') | ||
.auth('test', 'not-real-password') | ||
.expect(401, done); | ||
}); | ||
it('should respond with 200 since correct password is given', function(done) { | ||
request(liveServer) | ||
.get('/') | ||
.auth('test', 'test') | ||
.expect(200, done); | ||
}); | ||
}); |
var request = require('supertest'); | ||
var path = require('path'); | ||
// accept self-signed certificates | ||
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; | ||
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; | ||
function tests(liveServer) { | ||
it('should reply with a correct index file', function(done) { | ||
request(liveServer) | ||
.get('/index.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/Hello world/i) | ||
.expect(200, done); | ||
}); | ||
it('should support head request', function(done) { | ||
request(liveServer) | ||
.head('/index.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(200, done); | ||
}); | ||
it('should reply with a correct index file', function(done) { | ||
request(liveServer) | ||
.get('/index.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/Hello world/i) | ||
.expect(200, done); | ||
}); | ||
it('should support head request', function(done) { | ||
request(liveServer) | ||
.head('/index.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(200, done); | ||
}); | ||
} | ||
describe('https tests with external module', function() { | ||
var opts = { | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
https: path.join(__dirname, 'conf/https.conf.js') | ||
}; | ||
var liveServer = require("..").start(opts); | ||
tests(liveServer); | ||
after(function () { | ||
liveServer.close() | ||
}); | ||
var opts = { | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
https: path.join(__dirname, 'conf/https.conf.js'), | ||
}; | ||
var liveServer = require('..').start(opts); | ||
tests(liveServer); | ||
after(function() { | ||
liveServer.close(); | ||
}); | ||
}); | ||
describe('https tests with object', function() { | ||
var opts = { | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
https: require(path.join(__dirname, 'conf/https.conf.js')) | ||
}; | ||
var liveServer = require("..").start(opts); | ||
tests(liveServer); | ||
after(function () { | ||
liveServer.close() | ||
}); | ||
var opts = { | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
https: require(path.join(__dirname, 'conf/https.conf.js')), | ||
}; | ||
var liveServer = require('..').start(opts); | ||
tests(liveServer); | ||
after(function() { | ||
liveServer.close(); | ||
}); | ||
}); |
var request = require('supertest'); | ||
var path = require('path'); | ||
var liveServer1 = require('..').start({ | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
middleware: [ | ||
function setStatus(req, res, next) { | ||
res.statusCode = 201; | ||
next(); | ||
} | ||
] | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
middleware: [ | ||
function setStatus(req, res, next) { | ||
res.statusCode = 201; | ||
next(); | ||
}, | ||
], | ||
}); | ||
var liveServer2 = require('..').start({ | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
middleware: [ "example" ] | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
middleware: ['example'], | ||
}); | ||
var liveServer3 = require('..').start({ | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
middleware: [ path.join(__dirname, 'data', 'middleware.js') ] | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
middleware: [path.join(__dirname, 'data', 'middleware.js')], | ||
}); | ||
describe('middleware tests', function() { | ||
it("should respond with middleware function's status code", function(done) { | ||
request(liveServer1) | ||
.get('/') | ||
.expect(201, done); | ||
}); | ||
it("should respond with built-in middleware's status code", function(done) { | ||
request(liveServer2) | ||
.get('/') | ||
.expect(202, done); | ||
}); | ||
it("should respond with external middleware's status code", function(done) { | ||
request(liveServer3) | ||
.get('/') | ||
.expect(203, done); | ||
}); | ||
it("should respond with middleware function's status code", function(done) { | ||
request(liveServer1) | ||
.get('/') | ||
.expect(201, done); | ||
}); | ||
it("should respond with built-in middleware's status code", function(done) { | ||
request(liveServer2) | ||
.get('/') | ||
.expect(202, done); | ||
}); | ||
it("should respond with external middleware's status code", function(done) { | ||
request(liveServer3) | ||
.get('/') | ||
.expect(203, done); | ||
}); | ||
}); |
var request = require('supertest'); | ||
var path = require('path'); | ||
var liveServer = require('..').start({ | ||
root: path.join(__dirname, "data"), | ||
port: 0, | ||
open: false, | ||
mount: [ | ||
[ "/mounted", path.join(__dirname, "data", "sub") ], | ||
[ "/style", path.join(__dirname, "data", "style.css") ] | ||
] | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
mount: [ | ||
['/mounted', path.join(__dirname, 'data', 'sub')], | ||
['/style', path.join(__dirname, 'data', 'style.css')], | ||
], | ||
}); | ||
describe('mount tests', function() { | ||
it('should respond with sub.html', function(done) { | ||
request(liveServer) | ||
.get('/mounted/sub.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/Subdirectory/i) | ||
.expect(200, done); | ||
}); | ||
it('should respond with style.css', function(done) { | ||
request(liveServer) | ||
.get('/style') | ||
.expect('Content-Type', 'text/css; charset=UTF-8') | ||
.expect(/color/i) | ||
.expect(200, done); | ||
}); | ||
it('should respond with sub.html', function(done) { | ||
request(liveServer) | ||
.get('/mounted/sub.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/Subdirectory/i) | ||
.expect(200, done); | ||
}); | ||
it('should respond with style.css', function(done) { | ||
request(liveServer) | ||
.get('/style') | ||
.expect('Content-Type', 'text/css; charset=UTF-8') | ||
.expect(/color/i) | ||
.expect(200, done); | ||
}); | ||
}); | ||
@@ -5,25 +5,21 @@ var request = require('supertest'); | ||
var server1 = require('..').start({ | ||
root: path.join(__dirname, "data"), | ||
port: port, | ||
open: false | ||
root: path.join(__dirname, 'data'), | ||
port: port, | ||
open: false, | ||
}); | ||
var server2 = require('..').start({ | ||
root: path.join(__dirname, "data"), | ||
port: 0, | ||
open: false, | ||
proxy: [ | ||
["/server1", "http://localhost:" + port] | ||
] | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
proxy: [['/server1', 'http://localhost:' + port]], | ||
}); | ||
describe('proxy tests', function() { | ||
it('should respond with proxied content', function(done) { | ||
request(server2) | ||
.get('/server1/index.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/Hello world/i) | ||
.expect(200, done); | ||
}); | ||
it('should respond with proxied content', function(done) { | ||
request(server2) | ||
.get('/server1/index.html') | ||
.expect('Content-Type', 'text/html; charset=UTF-8') | ||
.expect(/Hello world/i) | ||
.expect(200, done); | ||
}); | ||
}); | ||
var request = require('supertest'); | ||
var path = require('path'); | ||
var liveServerSpa = require('..').start({ | ||
root: path.join(__dirname, "data"), | ||
port: 0, | ||
open: false, | ||
middleware: [ "spa" ] | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
middleware: ['spa'], | ||
}); | ||
var liveServerSpaIgnoreAssets = require('..').start({ | ||
root: path.join(__dirname, "data"), | ||
port: 0, | ||
open: false, | ||
middleware: [ "spa-ignore-assets" ] | ||
root: path.join(__dirname, 'data'), | ||
port: 0, | ||
open: false, | ||
middleware: ['spa-ignore-assets'], | ||
}); | ||
describe('spa tests', function(){ | ||
it('spa should redirect', function(done){ | ||
request(liveServerSpa) | ||
.get('/api') | ||
.expect('Location', /\/#\//) | ||
.expect(302, done); | ||
}); | ||
it('spa should redirect everything', function(done){ | ||
request(liveServerSpa) | ||
.get('/style.css') | ||
.expect('Location', /\/#\//) | ||
.expect(302, done); | ||
}); | ||
it('spa-ignore-assets should redirect something', function(done){ | ||
request(liveServerSpaIgnoreAssets) | ||
.get('/api') | ||
.expect('Location', /\/#\//) | ||
.expect(302, done); | ||
}); | ||
it('spa-ignore-assets should not redirect .css', function(done){ | ||
request(liveServerSpaIgnoreAssets) | ||
.get('/style.css') | ||
.expect(200, done); | ||
}); | ||
describe('spa tests', function() { | ||
it('spa should redirect', function(done) { | ||
request(liveServerSpa) | ||
.get('/api') | ||
.expect('Location', /\/#\//) | ||
.expect(302, done); | ||
}); | ||
it('spa should redirect everything', function(done) { | ||
request(liveServerSpa) | ||
.get('/style.css') | ||
.expect('Location', /\/#\//) | ||
.expect(302, done); | ||
}); | ||
it('spa-ignore-assets should redirect something', function(done) { | ||
request(liveServerSpaIgnoreAssets) | ||
.get('/api') | ||
.expect('Location', /\/#\//) | ||
.expect(302, done); | ||
}); | ||
it('spa-ignore-assets should not redirect .css', function(done) { | ||
request(liveServerSpaIgnoreAssets) | ||
.get('/style.css') | ||
.expect(200, done); | ||
}); | ||
}); |
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Dynamic require
Supply chain riskDynamic require can indicate the package is performing dangerous or unsafe dynamic code execution.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
Filesystem access
Supply chain riskAccesses the file system, and could potentially read sensitive data.
Found 1 instance in 1 package
1009
4.13%43738
-20.3%31
-8.82%2
-99.26%