Skip to content

Commit

Permalink
Allow using micro-dev programmatically (#89)
Browse files Browse the repository at this point in the history
  • Loading branch information
Elias Nygren authored and leo committed Dec 4, 2018
1 parent 099e3ca commit bda3bab
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
59 changes: 59 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Ensure that the loaded files and packages have the correct env
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

// Packages
const serve = require('micro/lib');
const ip = require('ip');
const chalk = require('chalk');
const boxen = require('boxen');

// Utilities
const log = require('./log');


/**
* micro-dev for programmatic usage
*
* Usage:
*
* require('micro-dev')({ silent: false, limit: '1mb', host: '::', port: PORT })(handler)
*/
module.exports = flags => handler => {
const module = flags.silent ? handler : log(handler, flags.limit);
const server = serve(module);

const sockets = [];
server.on('connection', socket => {
const index = sockets.push(socket);
socket.once('close', () => sockets.splice(index, 1));
});

server.listen(flags.port, flags.host, err => {
if (err) {
console.error('micro:', err.stack);
process.exit(1);
}

// message
const details = server.address();
const ipAddress = ip.address();
const url = `http://${ipAddress}:${details.port}`;
let message = chalk.green('Micro is running programmatically!');
message += '\n\n';

const host = flags.host === '::' ? 'localhost' : flags.host;
const localURL = `http://${host}:${details.port}`;

message += `• ${chalk.bold('Local: ')} ${localURL}\n`;
message += `• ${chalk.bold('On Your Network: ')} ${url}\n\n`;

const box = boxen(message, {
padding: 1,
borderColor: 'green',
margin: 1
});

// Print out the message
console.log(box);
});
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"name": "micro-dev",
"version": "3.0.0",
"main": "./lib/index.js",
"files": [
"bin",
"lib"
Expand Down

0 comments on commit bda3bab

Please sign in to comment.