GithubHelp home page GithubHelp logo

micro's Introduction

Micro — Asynchronous HTTP microservices

Features

  • Easy: Designed for usage with async and await
  • Fast: Ultra-high performance (even JSON parsing is opt-in)
  • Micro: The whole project is ~260 lines of code
  • Agile: Super easy deployment and containerization
  • Simple: Oriented for single purpose modules (function)
  • Standard: Just HTTP!
  • Explicit: No middleware - modules declare all dependencies
  • Lightweight: With all dependencies, the package weighs less than a megabyte

Disclaimer: Micro was created for use within containers and is not intended for use in serverless environments. For those using Vercel, this means that there is no requirement to use Micro in your projects as the benefits it provides are not applicable to the platform. Utility features provided by Micro, such as json, are readily available in the form of Serverless Function helpers.

Installation

Important: Micro is only meant to be used in production. In development, you should use micro-dev, which provides you with a tool belt specifically tailored for developing microservices.

To prepare your microservice for running in the production environment, firstly install micro:

npm install --save micro

Usage

Create an index.js file and export a function that accepts the standard http.IncomingMessage and http.ServerResponse objects:

module.exports = (req, res) => {
  res.end('Welcome to Micro');
};

Micro provides useful helpers but also handles return values – so you can write it even shorter!

module.exports = () => 'Welcome to Micro';

Next, ensure that the main property inside package.json points to your microservice (which is inside index.js in this example case) and add a start script:

{
  "main": "index.js",
  "scripts": {
    "start": "micro"
  }
}

Once all of that is done, the server can be started like this:

npm start

And go to this URL: http://localhost:3000 - 🎉

Command line

  micro - Asynchronous HTTP microservices

  USAGE

      $ micro --help
      $ micro --version
      $ micro [-l listen_uri [-l ...]] [entry_point.js]

      By default micro will listen on 0.0.0.0:3000 and will look first
      for the "main" property in package.json and subsequently for index.js
      as the default entry_point.

      Specifying a single --listen argument will overwrite the default, not supplement it.

  OPTIONS

      --help                              shows this help message

      -v, --version                       displays the current version of micro

      -l, --listen listen_uri             specify a URI endpoint on which to listen (see below) -
                                          more than one may be specified to listen in multiple places

  ENDPOINTS

      Listen endpoints (specified by the --listen or -l options above) instruct micro
      to listen on one or more interfaces/ports, UNIX domain sockets, or Windows named pipes.

      For TCP (traditional host/port) endpoints:

          $ micro -l tcp://hostname:1234

      For UNIX domain socket endpoints:

          $ micro -l unix:/path/to/socket.sock

      For Windows named pipe endpoints:

          $ micro -l pipe:\\.\pipe\PipeName

async & await

Examples

Micro is built for usage with async/await.

const sleep = require('then-sleep');

module.exports = async (req, res) => {
  await sleep(500);
  return 'Ready!';
};

Port Based on Environment Variable

When you want to set the port using an environment variable you can use:

micro -l tcp://0.0.0.0:$PORT

Optionally you can add a default if it suits your use case:

micro -l tcp://0.0.0.0:${PORT-3000}

${PORT-3000} will allow a fallback to port 3000 when $PORT is not defined.

Note that this only works in Bash.

Body parsing

Examples

For parsing the incoming request body we included an async functions buffer, text and json

const { buffer, text, json } = require('micro');

module.exports = async (req, res) => {
  const buf = await buffer(req);
  console.log(buf);
  // <Buffer 7b 22 70 72 69 63 65 22 3a 20 39 2e 39 39 7d>
  const txt = await text(req);
  console.log(txt);
  // '{"price": 9.99}'
  const js = await json(req);
  console.log(js.price);
  // 9.99
  return '';
};

API

buffer(req, { limit = '1mb', encoding = 'utf8' })
text(req, { limit = '1mb', encoding = 'utf8' })
json(req, { limit = '1mb', encoding = 'utf8' })
  • Buffers and parses the incoming body and returns it.
  • Exposes an async function that can be run with await.
  • Can be called multiple times, as it caches the raw request body the first time.
  • limit is how much data is aggregated before parsing at max. Otherwise, an Error is thrown with statusCode set to 413 (see Error Handling). It can be a Number of bytes or a string like '1mb'.
  • If JSON parsing fails, an Error is thrown with statusCode set to 400 (see Error Handling)

For other types of data check the examples

Sending a different status code

So far we have used return to send data to the client. return 'Hello World' is the equivalent of send(res, 200, 'Hello World').

const { send } = require('micro');

module.exports = async (req, res) => {
  const statusCode = 400;
  const data = { error: 'Custom error message' };

  send(res, statusCode, data);
};
send(res, statusCode, data = null)
  • Use require('micro').send.
  • statusCode is a Number with the HTTP status code, and must always be supplied.
  • If data is supplied it is sent in the response. Different input types are processed appropriately, and Content-Type and Content-Length are automatically set.
    • Stream: data is piped as an octet-stream. Note: it is your responsibility to handle the error event in this case (usually, simply logging the error and aborting the response is enough).
    • Buffer: data is written as an octet-stream.
    • object: data is serialized as JSON.
    • string: data is written as-is.
  • If JSON serialization fails (for example, if a cyclical reference is found), a 400 error is thrown. See Error Handling.

Programmatic use

You can use Micro programmatically by requiring Micro directly:

const http = require('http');
const sleep = require('then-sleep');
const { serve } = require('micro');

const server = new http.Server(
  serve(async (req, res) => {
    await sleep(500);
    return 'Hello world';
  }),
);

server.listen(3000);
serve(fn)
  • Use require('micro').serve.
  • Returns a function with the (req, res) => void signature. That uses the provided function as the request handler.
  • The supplied function is run with await. So it can be async
sendError(req, res, error)
  • Use require('micro').sendError.
  • Used as the default handler for errors thrown.
  • Automatically sets the status code of the response based on error.statusCode.
  • Sends the error.message as the body.
  • Stacks are printed out with console.error and during development (when NODE_ENV is set to 'development') also sent in responses.
  • Usually, you don't need to invoke this method yourself, as you can use the built-in error handling flow with throw.
createError(code, msg, orig)
  • Use require('micro').createError.
  • Creates an error object with a statusCode.
  • Useful for easily throwing errors with HTTP status codes, which are interpreted by the built-in error handling.
  • orig sets error.originalError which identifies the original error (if any).

Error Handling

Micro allows you to write robust microservices. This is accomplished primarily by bringing sanity back to error handling and avoiding callback soup.

If an error is thrown and not caught by you, the response will automatically be 500. Important: Error stacks will be printed as console.error and during development mode (if the env variable NODE_ENV is 'development'), they will also be included in the responses.

If the Error object that's thrown contains a statusCode property, that's used as the HTTP code to be sent. Let's say you want to write a rate limiting module:

const rateLimit = require('my-rate-limit');

module.exports = async (req, res) => {
  await rateLimit(req);
  // ... your code
};

If the API endpoint is abused, it can throw an error with createError like so:

if (tooMany) {
  throw createError(429, 'Rate limit exceeded');
}

Alternatively you can create the Error object yourself

if (tooMany) {
  const err = new Error('Rate limit exceeded');
  err.statusCode = 429;
  throw err;
}

The nice thing about this model is that the statusCode is merely a suggestion. The user can override it:

try {
  await rateLimit(req);
} catch (err) {
  if (429 == err.statusCode) {
    // perhaps send 500 instead?
    send(res, 500);
  }
}

If the error is based on another error that Micro caught, like a JSON.parse exception, then originalError will point to it. If a generic error is caught, the status will be set to 500.

In order to set up your own error handling mechanism, you can use composition in your handler:

const { send } = require('micro');

const handleErrors = (fn) => async (req, res) => {
  try {
    return await fn(req, res);
  } catch (err) {
    console.log(err.stack);
    send(res, 500, 'My custom error!');
  }
};

module.exports = handleErrors(async (req, res) => {
  throw new Error('What happened here?');
});

Testing

Micro makes tests compact and a pleasure to read and write. We recommend Node TAP or AVA, a highly parallel test framework with built-in support for async tests:

const http = require('http');
const { send, serve } = require('micro');
const test = require('ava');
const listen = require('test-listen');
const fetch = require('node-fetch');

test('my endpoint', async (t) => {
  const service = new http.Server(
    serve(async (req, res) => {
      send(res, 200, {
        test: 'woot',
      });
    }),
  );

  const url = await listen(service);
  const response = await fetch(url);
  const body = await response.json();

  t.deepEqual(body.test, 'woot');
  service.close();
});

Look at test-listen for a function that returns a URL with an ephemeral port every time it's called.

Contributing

  1. Fork this repository to your own GitHub account and then clone it to your local device
  2. Link the package to the global module directory: npm link
  3. Within the module you want to test your local development instance of Micro, just link it to the dependencies: npm link micro. Instead of the default one from npm, node will now use your clone of Micro!

You can run the tests using: npm test.

Credits

Thanks to Tom Yandell and Richard Hodgson for donating the name "micro" on npm!

Authors

micro's People

Contributors

albinekb avatar alexfreska avatar dmitriz avatar domachine avatar dotcypress avatar evenchange4 avatar floatdrop avatar fmiras avatar greenkeeper[bot] avatar greenkeeperio-bot avatar joeyrogues avatar kevin-roark avatar leerob avatar leo avatar lukeed avatar matheuss avatar mikeal avatar morgs32 avatar mxstbr avatar nkzawa avatar onbjerg avatar pmbanugo avatar qix- avatar rapzo avatar rauchg avatar thasophearak avatar thinkverse avatar timneutkens avatar tylkomat avatar walaszczykm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

micro's Issues

AMQP and web support?

I know the motto says right there: "Just HTTP!", but what if I wanted to use this same "micro"-approach and use AMQP as the transport layer? Could this be done without much hassle? Is there any extension or plugin for this?

Also, if I'm tied to HTTP for transport: what's the benefit of using the framework compared to, say, plain http from Node, Express, Hapi, Koa, Restify and the like?

In fact, how does micro play along with web frameworks such as those? Is it possible to integrate them in some way? Could I, for instance, define API routes in Express and send messages over to another microservice?

Cannot find module 'micro'

screen shot 2016-05-22 at 11 39 13 pm

I just wasted ~30 minutes because this package is now just exporting micro-core and that's what needs to be required for the npm start command described in the docs to work.

So instead of

import { send } from 'micro';

it should be

import { send } from 'micro-core';

Does not play well with debugger

If I do

/usr/local/bin/node --debug-brk=52090 --expose_debug_as=v8debug /Users/Morriz/Documents/workspace/playground/ms-api/node_modules/.bin/micro -p 3000 build/index.js

it never returns, making it impossible to debug ;|

Any ideas? I tried passing the app params behind --, but that gave an error:
micro: Error when importing /Users/Morriz/Documents/workspace/playground/ms-api/-p: Error: Cannot find module '/Users/Morriz/Documents/workspace/playground/ms-api/-p'

It would be nice if the script would allow param parsing behind --

> Error! file does not exist.

micro service.js

Error! "c:\Users\peira\MicroServiceProjects\n2x\service.js" does not exist.

but the file is true exist

Improve return

Thoughts about treating these two types differently?

  • If it's a Buffer, write it out as an octet stream
  • If it's a Stream, stream it out as an octet stream

cc @rase- @kevin-roark @nkzawa

Visualising requests

As suggested by @rauchg in #15, we should incorporate support for visualizing the requests in terms of the data flow, with built in JSON highlighting and prettifying, among other things.

Here's an example:

1b624cf2-e120-11e5-977a-d6508f8a19b0

micro (dev) and micro-serve

Right now micro has a convenient tool for preventing the setup of an entire Babel toolchain. Namely, you can run:

$ micro index.js

and index.js can use export, async, await and all the other goodies.

When going to production, this is unadvisable:

  1. npm install takes longer
  2. container images are larger
  3. bootup time increases

For 3, the solution right now is clear: use micro index during development, use micro --no-babel build/index in production.

For 1 and 2, it'll be great to have micro be the convenience tool, and micro-serve or micro-prod be the tool for serving in production.

micro will additionally incorporate support for visualizing the requests in terms of the data flow, with built in JSON highlighting and prettifying, among other things.

image

Repository: https://github.com/zeithq/micro-serve

Release 5.0.1 on npm

According to github, there's a 5.0.1 release but it wasn't published to npm it seems.

I was checking the commit logs, but it's a bit confusing with the renames (micro-core, micro-serve) and all. I'm not even 100% sure there's a difference between 5.0.0 and 5.0.1 - but if there is, an npm release would be appreciated.

Any suggestions on good logging practice?

More of a question than a bug, I was wondering how you have handled logging with micro?

I'd like to get some reasonable logging (e.g. response time, status, request content length etc.) out of my microservice. I've spent 5 mins playing around trying to get morgan to play with micro but it follows the middleware ideology which micro doesn't.

Any tips would be great! Thanks for open sourcing this 👍

How to use micro with two routes?

How would I design a service with more then one route?

For example I have a event-trace-api service where I trace all transactions in my app and expose a api where I can search for these events,

So basically I have 2 routes:
POST /v1/events
GET /v1/events/search

Following micro design I would have 2 separate servers, one for create and other for search, that looks too much for me,

Thanks

Micro organization?

I really like micro as an alternative to Koa - have you given any thought to creating something like a Micro JS community organization where people can host plugins etc?

Can't run micro 4.1.0

@rauchg Hi, it's me again - It's related to the update to [email protected] which doesn't have chalk as dependency (only devDependency) - Related: leo/args#17

⬢  microtest  micro --version
module.js:327
    throw err;
    ^

Error: Cannot find module 'chalk'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/julianduque/.nvm/versions/node/v4.4.5/lib/node_modules/micro/node_modules/args/dist/index.js:33:14)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)

Switch to use `http-errors` instead?

It won't be kind of breaking change. It has same signature and more "features" - more used and it is everywhere in koa/express/connect. ;] So I think it would be better for users to be some that they already know.

build/lib is not included in npm package

D:>micro
module.js:341
throw err;
^

Error: Cannot find module '../lib'
at Function.Module._resolveFilename (module.js:339:15)
at Function.Module._load (module.js:290:25)
at Module.require (module.js:367:17)
at require (internal/module.js:16:19)
at Object. (C:\Program Files (x86)\nodejs\node_modules\micro\buil
d\bin\micro:10:12)
at Module._compile (module.js:413:34)
at Object.Module._extensions..js (module.js:422:10)
at Module.load (module.js:357:32)
at Function.Module._load (module.js:314:12)
at Function.Module.runMain (module.js:447:10)

TypeScript compilation with --no-babel

I am trying the sleep.js example with TypeScript and avoid Babel Transpilation since TypeScript performs Transpilation.

The output I get from TypeScript is the following:

var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {
    return new Promise(function (resolve, reject) {
        generator = generator.call(thisArg, _arguments);
        function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }
        function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } }
        function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } }
        function step(verb, value) {
            var result = generator[verb](value);
            result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);
        }
        step("next", void 0);
    });
};
var micro_1 = require('micro');
var then_sleep_1 = require('then-sleep');
exports.default = function (req, res) {
    return __awaiter(this, void 0, Promise, function* () {
        yield then_sleep_1.default(500);
        micro_1.send(res, 200, 'Ready!');
    });
};

It appears to start fine however visiting localhost:3000 has the following error

TypeError: then_sleep_1.default is not a function

I suspect this might require changes to then-sleep module however it would be nice to see how the same example without the async/await.

What is the expected ES6 code (without async/await) for this sleep example?

Github Repo not in package.json

I wanted to write how I liked your package but when displaying it on npmjs.org, there's no direct link to this repository =)

You could add this github repository to the package.json for people to be able to switch between npm and the github pages more easily.

Does not work with babel-register and babel-polyfill

If I do a
node -r babel-register -r babel-polyfill node_modules/.bin/micro -p 3000 src/index.js
I still get errors about import/export statements:

micro: Error when importing ...
(function (exports, require, module, __filename, __dirname) { import ...
                                                              ^^^^^^

And yes, transpiling works (with preset-node6):
babel src --out-dir build

Any idea what might cause this?

Refusing to install micro as a dependency of itself

43 verbose stack Error: Refusing to install micro as a dependency of itself
43 verbose stack at checkSelf (/usr/local/lib/node_modules/npm/lib/install/validate-args.js:53:14)
43 verbose stack at Array. (/usr/local/lib/node_modules/npm/node_modules/slide/lib/bind-actor.js:15:8)
43 verbose stack at LOOP (/usr/local/lib/node_modules/npm/node_modules/slide/lib/chain.js:15:14)
43 verbose stack at chain (/usr/local/lib/node_modules/npm/node_modules/slide/lib/chain.js:20:5)
43 verbose stack at /usr/local/lib/node_modules/npm/lib/install/validate-args.js:16:5
43 verbose stack at /usr/local/lib/node_modules/npm/node_modules/slide/lib/async-map.js:52:35
43 verbose stack at Array.forEach (native)
43 verbose stack at /usr/local/lib/node_modules/npm/node_modules/slide/lib/async-map.js:52:11
43 verbose stack at Array.forEach (native)
43 verbose stack at asyncMap (/usr/local/lib/node_modules/npm/node_modules/slide/lib/async-map.js:51:8)
44 verbose cwd /Users/work/nodejs/micro
45 error Darwin 14.5.0
46 error argv "/usr/bin/node" "/usr/local/bin/npm" "install" "[email protected]"
47 error node v6.4.0
48 error npm v3.10.3
49 error code ENOSELF
50 error Refusing to install micro as a dependency of itself
51 error If you need help, you may report this error at:
51 error https://github.com/npm/npm/issues
52 verbose exit [ 1, true ]

Publish `micro-json` to npm?

The json() function in the micro lib is very useful on its own outside of micro contexts. Should we publish it to npm?

Unexpected token import

I'm trying to start the micro service but an error on the console is displayed:

micro: Error when importing /Users/miguhruiz/Dropbox/dev/bettercode-api/projects.js: /Users/miguhruiz/Dropbox/dev/bettercode-api/projects.js:3
import { send, json } from 'micro'
^^^^^^
SyntaxError: Unexpected token import
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:528:28)
    at Object.require.extensions..js (/Users/miguhruiz/.nvm/versions/node/v6.4.0/lib/node_modules/micro/node_modules/async-to-gen/register.js:9:12)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at Module.require (module.js:483:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/miguhruiz/.nvm/versions/node/v6.4.0/lib/node_modules/micro/bin/micro:60:9)
    at Module._compile (module.js:556:32)

Run on a certain port

I have this in the package.json:

"scripts": {
  "start": "micro app.js -p 8000"
},

but the app still starts on port 3000.

Am I doing something wrong or this would be a known bug?

Generator error

There seems to be an issue with generators, perhaps from babel-plugin-transform-async-to-generator.

This works:

export default async function(req, res) {
  ...
}

This doesn't:

async function anything(req, res) {
  ...
}

export default anything;

This will give me the following error:

> [email protected] start /Users/daryl/Desktop/mic
> micro --port 9000 index.js

/Users/daryl/Desktop/mic/index.js:8
  var ref = (0, _asyncToGenerator3.default)(_regenerator2.default.mark(function _callee() {
                                  ^

TypeError: Cannot read property 'default' of undefined
    at /Users/daryl/Desktop/mic/index.js:8:35
    at Object.<anonymous> (/Users/daryl/Desktop/mic/index.js:22:2)
    at Module._compile (module.js:398:26)
    at loader (/Users/daryl/Desktop/mic/node_modules/babel-register/lib/node.js:128:5)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/daryl/Desktop/mic/node_modules/babel-register/lib/node.js:138:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/daryl/Desktop/mic/node_modules/micro/build/bin/micro:67:11)

Error parsing post request data

Hello,
I am trying use micro to read data from a post request. This is the error I am running into:

TypeError: "string" must be a string, Buffer, or ArrayBuffer
    at Function.byteLength (buffer.js:362:11)
    at send (/Users/nodatall/Documents/shuffle/retext-intepreter/node_modules/micro/dist/index.js:102:46)
    at /Users/nodatall/Documents/shuffle/retext-intepreter/node_modules/micro/dist/index.js:36:7
    at Generator.next (<anonymous>)
    at c (/Users/Sylvan/Documents/shuffle/retext-intepreter/node_modules/micro/dist/index.js:129:99)
    at process._tickCallback (internal/process/next_tick.js:103:7)

This is the code I have written:

const proofReadService = ( request, response ) => {
   return async function() {
    const data = await json(request)
    send( response, 200, 'hello world 👏')
  }
}

const cors = microCors({ allowMethods: ['PUT', 'POST'] })
module.exports = cors(proofReadService)

Here are the request headers:

{ host: 'localhost:3000',
  connection: 'keep-alive',
  'content-length': '34',
  'postman-token': '4d7d2362-415b-2e47-29bc-fc2a938557b7',
  'cache-control': 'no-cache',
  origin: 'chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',
  'content-type': 'application/json',
  accept: '*/*',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.8' } 

Any idea what might be going on? Thanks a bunch!

SyntaxError: Unexpected token export

On fresh install with:

npm init
npm install --save micro

and the following in index.js

const { send } = require('micro');

export default async function (req, res) {
  send(res, 200);
}

running micro -p 3000 yields:

export default function (req, res) {return __async(function*(){
^^^^^^
SyntaxError: Unexpected token export
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:528:28)
    at Object.require.extensions..js (/home/allain/personal/now/chordie-api/node_modules/async-to-gen/register.js:9:12)
    at Module.load (module.js:473:32)

I'm running Node v6.5.0 and micro version installed is 6.0.2

Return

export default function (req, res) {
  return 'woot';
}

and

export default function () {
  return { a: 'woot' };
}

will be equivalent to:

send(res, 200, 'woot');
send(res, 200, { a: 'woot' });

v6.0.1, published to npm yet?

running npm install micro does not install the latest version, instead it only install version 5.0.1.
cleared cache and manually specifying the version npm install [email protected] does not work as well. or do I miss anything?

Start script without npm

Hi,

I want to start my app without npm but it doesn't work.

I have a code like this in index.js:

module.exports = async function (req, res) {
  ...
}

And starting it with npm works fine.

But if I try something like:

const srv = micro(async function (req, res) {
  ...
})
srv.listen(3000)

And starting it with node index.js I get an error: Unexpected token function

I'm using node v7.3.0.

Thanks

Explicit. No middleware ?

Explicit. No middleware. Modules declare all dependencies
What does it mean by no middleware? why you design it like this.

using `micro file.js` on readme example doesn't work

for recollection the readme example is

import { send } from 'micro';
import sleep from 'then-sleep';
export default async function (req, res) {
  await sleep(500);
  send(res, 200, 'Ready!');
}

A solution to this would be to either

  • replace with import { send } from 'micro-core'
  • reexport micro-core from micro (which has no main field in its package)

Cannot run micro 4.0.0

⬢  microtest  micro -p 7001 one.js
module.js:327
    throw err;
    ^

Error: Cannot find module 'babel-plugin-syntax-async-functions'
    at Function.Module._resolveFilename (module.js:325:15)
    at Function.Module._load (module.js:276:25)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/Users/julianduque/.nvm/versions/node/v4.4.5/lib/node_modules/micro/build/bin/micro:20:40)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Function.Module.runMain (module.js:441:10)

Support host argument

micro-core already supports --host argument. Handy to listen on localhost behind a reverse proxy, for instance. I have some code here: millette@3e81493

I could submit a complete PR, but with the above I had to include dist/ in git to make it easier to install.

CLI transpiler doesn't run in Windows environment

I've been playing with the code here trying to get the async/await calls firing which I understand use the is-async-supported, and async-to-gen libraries. As a basic example, I follow the instructions for installing the example provided: https://github.com/zeit/micro/tree/master/examples/external-api-call

Pulling the code in on mac, npm install, npm run start. This works as expected.

Doing the identical thing in Git Bash on Win 10 results in a reference to the async function.

micro

This code is not being transpiled. It may be an issue with that specific library which maybe I should refer this issue to that repo.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.