diff --git a/lib/server.js b/lib/server.js index 588ed0e..f20e3ca 100644 --- a/lib/server.js +++ b/lib/server.js @@ -2,7 +2,7 @@ const connect = require('connect'); const http = require('http'); -const { underline } = require('picocolors'); +const { underline, bold } = require('picocolors'); const Promise = require('bluebird'); const open = require('open'); const net = require('net'); @@ -21,14 +21,19 @@ module.exports = function(args) { return this.watch(); }).then(() => startServer(http.createServer(app), port, ip)).then(server => { + const listeningAddress = getListeningAddress(server.address()); + this.log.info('hexo-server listening on %s . Press Ctrl+C to stop.', bold(listeningAddress)); + + return server; + }).then(server => { const addr = server.address(); - const addrString = formatAddress(ip || addr.address, addr.port, root); + const localAddress = getLocalAddress(ip || addr.address, addr.port, root); - this.log.info('Hexo is running at %s . Press Ctrl+C to stop.', underline(addrString)); + this.log.info('Preview your site via: %s ', underline(localAddress)); this.emit('server'); if (args.o || args.open) { - open(addrString); + open(localAddress); } return server; @@ -69,7 +74,18 @@ function checkPort(ip, port) { }).then(() => { server.close(); }); } -function formatAddress(ip, port, root) { +function getListeningAddress(serverAddress) { + const {address, port, family} = serverAddress; + let host; + if (family === 'IPv6') { + host = `[${address}]`; + } else { + host = address; + } + return `${host}:${port}`; +} + +function getLocalAddress(ip, port, root) { let hostname = ip; if (ip === '0.0.0.0' || ip === '::') { hostname = 'localhost'; diff --git a/test/index.js b/test/index.js index 93d4277..4c558d3 100644 --- a/test/index.js +++ b/test/index.js @@ -259,7 +259,7 @@ describe('server', () => { stub.callsFake(spy); return Promise.using(prepareServer(), app => { - spy.args[1][1].should.contain('localhost'); + spy.args[2][1].should.contain('localhost'); }).finally(() => { stub.restore(); }); @@ -271,7 +271,21 @@ describe('server', () => { stub.callsFake(spy); return Promise.using(prepareServer({ip: '::'}), app => { - spy.args[1][1].should.contain('localhost'); + spy.args[2][1].should.contain('localhost'); + }).finally(() => { + stub.restore(); + }); + }); + + it('display listening address', () => { + const spy = sinon.spy(); + const stub = sinon.stub(hexo.log, 'info'); + stub.callsFake(spy); + + return Promise.using(prepareServer({ip: 'localhost'}), app => { + spy.args[1][1].should.satisfy(listenAddress => { + return listenAddress.includes('::1') || listenAddress.includes('127.0.0.1'); + }); }).finally(() => { stub.restore(); });