diff --git a/CHANGELOG.md b/CHANGELOG.md index a5d7afaa0..d97fdf0b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,6 @@ +- Added: Use node-portfinder to avoid error when port is used + ([#320](https://github.com/MoOx/statinamic/issues/320)) + # 0.9.3 - 2016-04-04 ## Boilerplate diff --git a/__tests__/cli.js b/__tests__/cli.js index 4a1a614d2..2f34150b4 100644 --- a/__tests__/cli.js +++ b/__tests__/cli.js @@ -47,9 +47,42 @@ test.cb("should NOT throw if a CLI flag is recognized", (t) => { } ) + // ...or be ok quickly + // (so we assume it's ok and kill the process, we don't need the actual build) const timeout = setTimeout(() => { child.kill() t.pass() t.end() }, 500) }) + +test.cb("should NOT throw if port is used", (t) => { + const app = require("express")() + + const server = app.listen(8081, (err) => { + if (err) { + t.fail() + t.end() + } + + const child = exec( + `${ statinamic } start --devPort=8081`, execOpts, + + (err) => { + if (err) { + console.log(err) + clearTimeout(timeout) + t.fail() + t.end() + } + } + ) + + const timeout = setTimeout(() => { + child.kill() + server.close() + t.pass() + t.end() + }, 2000) + }) +}) diff --git a/package.json b/package.json index 265e4f9c0..3b5b03aee 100644 --- a/package.json +++ b/package.json @@ -54,6 +54,7 @@ "lru-memoize": "^1.0.0", "mkdirp": "^0.5.1", "opn": "^3.0.2", + "portfinder": "^1.0.2", "redbox-react": "^1.2.2", "remark": "^4.1.1", "remark-autolink-headings": "^3.0.0", diff --git a/src/builder/server.js b/src/builder/server.js index 2fe84707a..fe09bf7cd 100644 --- a/src/builder/server.js +++ b/src/builder/server.js @@ -7,6 +7,7 @@ import WebpackErrorNotificationPlugin from "webpack-error-notification" import opn from "opn" import debug from "debug" +import portFinder from "portfinder" import collection from "../content-loader/cache.js" import urlAsHtml from "../static/to-html/url-as-html" @@ -196,17 +197,26 @@ export default (options = {}) => { // THAT'S IT const { devHost, devPort } = config - server.listen(devPort, devHost, (err) => { - if (err) { - log(err) + portFinder.basePort = devPort - return + portFinder.getPort((err, port) => { + if (err) { + throw err } - const href = `http://${ devHost }:${ devPort }${ config.baseUrl.pathname }` - log(`Dev server started on ${ href }`) - if (config.open) { - opn(href.replace(devHost, "localhost")) + + if (port !== devHost) { + log(`Port ${ devPort } is not available. Using port ${ port } instead.`) } + server.listen(port, devHost, (err) => { + if (err) { + throw err + } + const href = `http://${ devHost }:${ port }${ config.baseUrl.pathname }` + log(`Dev server started on ${ href }`) + if (config.open) { + opn(href.replace(devHost, "localhost")) + } + }) }) }