<commit_before>![](https://cldup.com/JDmmHX3uhF.svg)

_**Micro —** Async ES6 HTTP microservices_

[![Build Status](https://travis-ci.org/zeit/micro.svg?branch=master)](https://travis-ci.org/zeit/micro)
[![Slack Channel](https://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/)
[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)

## Features

* **Easy**. Designed for usage with `async` and `await` ([more](https://zeit.co/blog/async-and-await))
* **Fast**. Ultra-high performance (even JSON parsing is opt-in).
* **Micro**. The whole project is ~100 lines of code.
* **Agile**. Super easy deployment and containerization.
* **Simple**. Oriented for single purpose modules (function).
* **Explicit**. No middleware. Modules declare all dependencies.
* **Standard**. Just HTTP!
* **Lightweight**. The package is small and the `async` transpilation fast and transparent

## Example

The following example `sleep.js` will wait before responding (without blocking!)

```js
const { send } = require('micro');
const sleep = require('then-sleep');
module.exports = async function (req, res) {
  await sleep(500);
  send(res, 200, 'Ready!');
}
```

To run the microservice on port `3000`, use the `micro` command:

```bash
$ micro -p 3000 sleep.js
```

To run the microservice on port `3000` and localhost instead of listening on every interface, use the `micro` command:

```bash
$ micro -p 3000 -H localhost sleep.js
```

## Documentation

### Installation

**Note**: `micro` requires Node `6.0.0` or later

Install from NPM:

```js
$ npm init
$ npm install micro --save
```

Then in your `package.json`:

```js
"main": "index.js",
"scripts": {
  "start": "micro -p 3000"
}
```

Then write your `index.js` (see above for an example). To run your
app and make it listen on `http://localhost:3000` run:

```bash
$ npm start
```

### API

#### micro
**`micro(fn)`**

- This function is exposed as the `default` export.
- Use `require('micro')`.
- Returns a [`http.Server`](https://nodejs.org/dist/latest-v4.x/docs/api/http.html#http_class_http_server) that uses the provided `fn` as the request handler.
- The supplied function is run with `await`. It can be `async`!
- Example:

  ```js
  const micro = require('micro');
  const sleep = require('then-sleep');
  const srv = micro(async function (req, res) {
    await sleep(500);
    res.writeHead(200);
    res.end('woot');
  });
  srv.listen(3000);
  ```

#### json

**`json(req, { limit = '1mb' })`**

- Use `require('micro').json`.
- Buffers and parses the incoming body and returns it.
- Exposes an `async` function that can be run with  `await`.
- `limit` is how much data is aggregated before parsing at max. Otherwise, an `Error` is thrown with `statusCode` set to `413` (see [Error Handling](#error-handling)). It can be a `Number` of bytes or [a string](https://www.npmjs.com/package/bytes) like `'1mb'`.
- If JSON parsing fails, an `Error` is thrown with `statusCode` set to `400` (see [Error Handling](#error-handling))
- Example:

  ```js
  const { json, send } = require('micro');
  module.exports = async function (req, res) {
    const data = await json(req);
    console.log(data.price);
    send(res, 200);
  }
  ```

#### send

**`send(res, statusCode, data = null)`**

- Use `require('micro').send`.
- `statusCode` is a `Number` with the HTTP error 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](#error-handling).
- Example

  ```js
  const { send } = require('micro')
  module.exports = async function (req, res) {
    send(res, 400, { error: 'Please use a valid email' });
  }
  ```

#### return

**`return val;`**

- Returning `val` from your function is shorthand for: `send(res, 200, val)`.
- Example

  ```js
  module.exports = default function (req, res) {
    return {message: 'Hello!'};
  }
  ```

- Returning a promise works as well!
- Example

  ```js
  const sleep = require('then-sleep')
  module.exports = async function(req, res) => {
    return new Promise(async (resolve) => {
      await sleep(100);
      resolve('I Promised');
    });
  }
  ```

#### sendError

**`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.
- During development (when `NODE_ENV` is set to `'development'`), stacks are printed out with `console.error` and also sent in responses.
- Usually, you don't need to invoke this method yourself, as you can use the [built-in error handling](error-handling) flow with `throw`.
<commit_msg>Fix README.md code examples (#108)<commit_after>![](https://cldup.com/JDmmHX3uhF.svg)

_**Micro —** Async ES6 HTTP microservices_

[![Build Status](https://travis-ci.org/zeit/micro.svg?branch=master)](https://travis-ci.org/zeit/micro)
[![Slack Channel](https://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/)
[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)

## Features

* **Easy**. Designed for usage with `async` and `await` ([more](https://zeit.co/blog/async-and-await))
* **Fast**. Ultra-high performance (even JSON parsing is opt-in).
* **Micro**. The whole project is ~100 lines of code.
* **Agile**. Super easy deployment and containerization.
* **Simple**. Oriented for single purpose modules (function).
* **Explicit**. No middleware. Modules declare all dependencies.
* **Standard**. Just HTTP!
* **Lightweight**. The package is small and the `async` transpilation fast and transparent

## Example

The following example `sleep.js` will wait before responding (without blocking!)

```js
const { send } = require('micro');
const sleep = require('then-sleep');
module.exports = async function (req, res) {
  await sleep(500);
  send(res, 200, 'Ready!');
}
```

To run the microservice on port `3000`, use the `micro` command:

```bash
$ micro -p 3000 sleep.js
```

To run the microservice on port `3000` and localhost instead of listening on every interface, use the `micro` command:

```bash
$ micro -p 3000 -H localhost sleep.js
```

## Documentation

### Installation

**Note**: `micro` requires Node `6.0.0` or later

Install from NPM:

```js
$ npm init
$ npm install micro --save
```

Then in your `package.json`:

```js
"main": "index.js",
"scripts": {
  "start": "micro -p 3000"
}
```

Then write your `index.js` (see above for an example). To run your
app and make it listen on `http://localhost:3000` run:

```bash
$ npm start
```

### API

#### micro
**`micro(fn)`**

- This function is exposed as the `default` export.
- Use `require('micro')`.
- Returns a [`http.Server`](https://nodejs.org/dist/latest-v4.x/docs/api/http.html#http_class_http_server) that uses the provided `fn` as the request handler.
- The supplied function is run with `await`. It can be `async`!
- Example:

  ```js
  const micro = require('micro');
  const sleep = require('then-sleep');
  const srv = micro(async function (req, res) {
    await sleep(500);
    res.writeHead(200);
    res.end('woot');
  });
  srv.listen(3000);
  ```

#### json

**`json(req, { limit = '1mb' })`**

- Use `require('micro').json`.
- Buffers and parses the incoming body and returns it.
- Exposes an `async` function that can be run with  `await`.
- `limit` is how much data is aggregated before parsing at max. Otherwise, an `Error` is thrown with `statusCode` set to `413` (see [Error Handling](#error-handling)). It can be a `Number` of bytes or [a string](https://www.npmjs.com/package/bytes) like `'1mb'`.
- If JSON parsing fails, an `Error` is thrown with `statusCode` set to `400` (see [Error Handling](#error-handling))
- Example:

  ```js
  const { json, send } = require('micro');
  module.exports = async function (req, res) {
    const data = await json(req);
    console.log(data.price);
    send(res, 200);
  }
  ```

#### send

**`send(res, statusCode, data = null)`**

- Use `require('micro').send`.
- `statusCode` is a `Number` with the HTTP error 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](#error-handling).
- Example

  ```js
  const { send } = require('micro')
  module.exports = async function (req, res) {
    send(res, 400, { error: 'Please use a valid email' });
  }
  ```

#### return

**`return val;`**

- Returning `val` from your function is shorthand for: `send(res, 200, val)`.
- Example

  ```js
  module.exports = function (req, res) {
    return {message: 'Hello!'};
  }
  ```

- Returning a promise works as well!
- Example

  ```js
  const sleep = require('then-sleep')
  module.exports = async function (req, res) {
    return new Promise(async (resolve) => {
      await sleep(100);
      resolve('I Promised');
    });
  }
  ```

#### sendError

**`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.
- During development (when `NODE_ENV` is set to `'development'`), stacks are printed out with `console.error` and also sent in responses.
- Usually, you don't need to invoke this method yourself, as you can use the [built-in error handling](error-handling) flow with `throw`.

{'fraction_non_alphanumeric': 0.15942166841053934, 'fraction_numerical': 0.014553410063730619, 'mean_word_length': 3.9758637008991955, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 6, 'https://': 20, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6008908', 'n_tokens_mistral': 3549, 'n_tokens_neox': 3306, 'n_words': 1200}