# Multer and more

# Multer

참고

        This page was generated from the [multer README](https://github.com/expressjs/multer).

# Multer

Multer is a node.js middleware for handling `multipart/form-data`, which is primarily used for uploading files. It is written
on top of [busboy](https://github.com/mscdex/busboy) for maximum efficiency.

**NOTE**: Multer will not process any form which is not multipart (`multipart/form-data`).

## Translations

This README is also available in other languages:

|  |  |
| --- | --- |
| العربية | Arabic |
| 简体中文 | Chinese |
| Français | French |
| 한국어 | Korean |
| Português | Portuguese (BR) |
| Русский язык | Russian |
| Español | Spanish |
| O’zbek tili | Uzbek |
| Việt Nam | Vietnamese |

## Installation

```
$ npm install multer
```

## Usage

Multer adds a `body` object and a `file` or `files` object to the `request` object. The `body` object contains the values of the text fields of the form, the `file` or `files` object contains the files uploaded via the form.

Basic usage example:

Don’t forget the `enctype="multipart/form-data"` in your form.

```
<form action="/profile" method="post" enctype="multipart/form-data">
  <input type="file" name="avatar" />
</form>
```

```
const express = require('express')
const multer  = require('multer')
const upload = multer({ dest: 'uploads/' })

const app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

const uploadMiddleware = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', uploadMiddleware, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
})
```

In case you need to handle a text-only multipart form, you should use the `.none()` method:

```
const express = require('express')
const app = express()
const multer  = require('multer')
const upload = multer()

app.post('/profile', upload.none(), function (req, res, next) {
  // req.body contains the text fields
})
```

Here’s an example on how multer is used in a HTML form. Take special note of the `enctype="multipart/form-data"` and `name="uploaded_file"` fields:

```
<form action="/stats" enctype="multipart/form-data" method="post">
  <div class="form-group">
    <input type="file" class="form-control-file" name="uploaded_file">
    <input type="text" class="form-control" placeholder="Number of speakers" name="nspeakers">
    <input type="submit" value="Get me the stats!" class="btn btn-default">
  </div>
</form>
```

Then in your javascript file you would add these lines to access both the file and the body. It is important that you use the `name` field value from the form in your upload function. This tells multer which field on the request it should look for the files in. If these fields aren’t the same in the HTML form and on your server, your upload will fail:

```
const multer  = require('multer')
const upload = multer({ dest: './public/data/uploads/' })
app.post('/stats', upload.single('uploaded_file'), function (req, res) {
  // req.file is the name of your file in the form above, here 'uploaded_file'
  // req.body will hold the text fields, if there were any
  console.log(req.file, req.body)
});
```

## API

### File information

Each file contains the following information:

| Key | Description | Note |
| --- | --- | --- |
| fieldname | Field name specified in the form |  |
| originalname | Name of the file on the user’s computer |  |
| encoding | Encoding type of the file |  |
| mimetype | Mime type of the file |  |
| size | Size of the file in bytes |  |
| destination | The folder to which the file has been saved | DiskStorage |
| filename | The name of the file within thedestination | DiskStorage |
| path | The full path to the uploaded file | DiskStorage |
| buffer | ABufferof the entire file | MemoryStorage |

### multer(opts)

Multer accepts an options object, the most basic of which is the `dest`
property, which tells Multer where to upload the files. In case you omit the
options object, the files will be kept in memory and never written to disk.

By default, Multer will rename the files so as to avoid naming conflicts. The
renaming function can be customized according to your needs.

The following are the options that can be passed to Multer.

| Key | Description |
| --- | --- |
| destorstorage | Where to store the files |
| fileFilter | Function to control which files are accepted |
| limits | Limits of the uploaded data |
| preservePath | Keep the full path of files instead of just the base name |

In an average web app, only `dest` might be required, and configured as shown in
the following example.

```
const upload = multer({ dest: 'uploads/' })
```

If you want more control over your uploads, you’ll want to use the `storage`
option instead of `dest`. Multer ships with storage engines `DiskStorage`
and `MemoryStorage`; More engines are available from third parties.

#### .single(fieldname)

Accept a single file with the name `fieldname`. The single file will be stored
in `req.file`.

#### .array(fieldname[, maxCount])

Accept an array of files, all with the name `fieldname`. Optionally error out if
more than `maxCount` files are uploaded. The array of files will be stored in
`req.files`.

#### .fields(fields)

Accept a mix of files, specified by `fields`. An object with arrays of files
will be stored in `req.files`.

`fields` should be an array of objects with `name` and optionally a `maxCount`.
Example:

```
[
  { name: 'avatar', maxCount: 1 },
  { name: 'gallery', maxCount: 8 }
]
```

#### .none()

Accept only text fields. If any file upload is made, error with code
“LIMIT_UNEXPECTED_FILE” will be issued.

#### .any()

Accepts all files that comes over the wire. An array of files will be stored in
`req.files`.

**WARNING:** Make sure that you always handle the files that a user uploads.
Never add multer as a global middleware since a malicious user could upload
files to a route that you didn’t anticipate. Only use this function on routes
where you are handling the uploaded files.

### storage

#### DiskStorage

The disk storage engine gives you full control on storing files to disk.

```
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
    cb(null, file.fieldname + '-' + uniqueSuffix)
  }
})

const upload = multer({ storage: storage })
```

There are two options available, `destination` and `filename`. They are both
functions that determine where the file should be stored.

`destination` is used to determine within which folder the uploaded files should
be stored. This can also be given as a `string` (e.g. `'/tmp/uploads'`). If no
`destination` is given, the operating system’s default directory for temporary
files is used.

**Note:** You are responsible for creating the directory when providing
`destination` as a function. When passing a string, multer will make sure that
the directory is created for you.

`filename` is used to determine what the file should be named inside the folder.
If no `filename` is given, each file will be given a random name that doesn’t
include any file extension.

**Note:** Multer will not append any file extension for you, your function
should return a filename complete with a file extension.

Each function gets passed both the request (`req`) and some information about
the file (`file`) to aid with the decision.

Note that `req.body` might not have been fully populated yet. It depends on the
order that the client transmits fields and files to the server.

For understanding the calling convention used in the callback (needing to pass
null as the first param), refer to
[Node.js error handling](https://web.archive.org/web/20220417042018/https://www.joyent.com/node-js/production/design/errors)

#### MemoryStorage

The memory storage engine stores the files in memory as `Buffer` objects. It
doesn’t have any options.

```
const storage = multer.memoryStorage()
const upload = multer({ storage: storage })
```

When using memory storage, the file info will contain a field called
`buffer` that contains the entire file.

**WARNING**: Uploading very large files, or relatively small files in large
numbers very quickly, can cause your application to run out of memory when
memory storage is used.

### limits

An object specifying the size limits of the following optional properties. Multer passes this object into busboy directly, and the details of the properties can be found on [busboy’s page](https://github.com/mscdex/busboy#busboy-methods).

The following integer values are available:

| Key | Description | Default |
| --- | --- | --- |
| fieldNameSize | Max field name size | 100 bytes |
| fieldSize | Max field value size (in bytes) | 1MB |
| fields | Max number of non-file fields | Infinity |
| fileSize | For multipart forms, the max file size (in bytes) | Infinity |
| files | For multipart forms, the max number of file fields | Infinity |
| parts | For multipart forms, the max number of parts (fields + files) | Infinity |
| headerPairs | For multipart forms, the max number of header key=>value pairs to parse | 2000 |

Specifying the limits can help protect your site against denial of service (DoS) attacks.

### fileFilter

Set this to a function to control which files should be uploaded and which
should be skipped. The function should look like this:

```
function fileFilter (req, file, cb) {

  // The function should call `cb` with a boolean
  // to indicate if the file should be accepted

  // To reject this file pass `false`, like so:
  cb(null, false)

  // To accept the file pass `true`, like so:
  cb(null, true)

  // You can always pass an error if something goes wrong:
  cb(new Error('I don\'t have a clue!'))

}
```

## Error handling

When encountering an error, Multer will delegate the error to Express. You can
display a nice error page using [the standard express way](http://expressjs.com/guide/error-handling.html).

If you want to catch errors specifically from Multer, you can call the
middleware function by yourself. Also, if you want to catch only [the Multer errors](https://github.com/expressjs/multer/blob/main/lib/multer-error.js), you can use the `MulterError` class that is attached to the `multer` object itself (e.g. `err instanceof multer.MulterError`).

```
const multer = require('multer')
const upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      // A Multer error occurred when uploading.
    } else if (err) {
      // An unknown error occurred when uploading.
    }

    // Everything went fine.
  })
})
```

## Custom storage engine

For information on how to build your own storage engine, see [Multer Storage Engine](https://github.com/expressjs/multer/blob/main/StorageEngine.md).

## License

[MIT](https://expressjs.com/ko/resources/middleware/LICENSE)

---

# response

참고

        This page was generated from the [response-time README](https://github.com/expressjs/response-time).

# response-time

Response time for Node.js servers.

This module creates a middleware that records the response time for
requests in HTTP servers. The “response time” is defined here as the
elapsed time from when a request enters this middleware to when the
headers are written out to the client.

## Installation

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[npm installcommand](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```
$ npm install response-time
```

## API

  eslint-disable no-unused-vars

```
var responseTime = require('response-time')
```

### responseTime([options])

Create a middleware that adds a `X-Response-Time` header to responses. If
you don’t want to use this module to automatically set a header, please
see the section about [responseTime(fn)](#responsetimefn).

#### Options

The `responseTime` function accepts an optional `options` object that may
contain any of the following keys:

##### digits

The fixed number of digits to include in the output, which is always in
milliseconds, defaults to `3` (ex: `2.300ms`).

##### header

The name of the header to set, defaults to `X-Response-Time`.

##### suffix

Boolean to indicate if units of measurement suffix should be added to
the output, defaults to `true` (ex: `2.300ms` vs `2.300`).

### responseTime(fn)

Create a new middleware that records the response time of a request and
makes this available to your own function `fn`. The `fn` argument will be
invoked as `fn(req, res, time)`, where `time` is a number in milliseconds.

## Examples

### express/connect

```
var express = require('express')
var responseTime = require('response-time')

var app = express()

app.use(responseTime())

app.get('/', function (req, res) {
  res.send('hello, world!')
})
```

### vanilla http server

```
var finalhandler = require('finalhandler')
var http = require('http')
var responseTime = require('response-time')

// create "middleware"
var _responseTime = responseTime()

http.createServer(function (req, res) {
  var done = finalhandler(req, res)
  _responseTime(req, res, function (err) {
    if (err) return done(err)

    // respond to request
    res.setHeader('content-type', 'text/plain')
    res.end('hello, world!')
  })
})
```

### response time metrics

```
var express = require('express')
var responseTime = require('response-time')
var StatsD = require('node-statsd')

var app = express()
var stats = new StatsD()

stats.socket.on('error', function (error) {
  console.error(error.stack)
})

app.use(responseTime(function (req, res, time) {
  var stat = (req.method + req.url).toLowerCase()
    .replace(/[:.]/g, '')
    .replace(/\//g, '_')
  stats.timing(stat, time)
}))

app.get('/', function (req, res) {
  res.send('hello, world!')
})
```

## License

[MIT](https://expressjs.com/ko/resources/middleware/LICENSE)

---

# serve

참고

        This page was generated from the [serve-favicon README](https://github.com/expressjs/serve-favicon).

# serve-favicon

Node.js middleware for serving a favicon.

A favicon is a visual cue that client software, like browsers, use to identify
a site. For an example and more information, please visit
[the Wikipedia article on favicons](https://en.wikipedia.org/wiki/Favicon).

Why use this module?

- User agents request `favicon.ico` frequently and indiscriminately, so you
  may wish to exclude these requests from your logs by using this middleware
  before your logger middleware.
- This module caches the icon in memory to improve performance by skipping
  disk access.
- This module provides an `ETag` based on the contents of the icon, rather
  than file system properties.
- This module will serve with the most compatible `Content-Type`.

**Note** This module is exclusively for serving the “default, implicit favicon”,
which is `GET /favicon.ico`. For additional vendor-specific icons that require
HTML markup, additional middleware is required to serve the relevant files, for
example [serve-static](https://npmjs.org/package/serve-static).

## Install

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[npm installcommand](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```
$ npm install serve-favicon
```

## API

### favicon(path, options)

Create new middleware to serve a favicon from the given `path` to a favicon file.
`path` may also be a `Buffer` of the icon to serve.

#### Options

Serve favicon accepts these properties in the options object.

##### maxAge

The `cache-control` `max-age` directive in `ms`, defaulting to 1 year. This can
also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme)
module.

## Examples

Typically this middleware will come very early in your stack (maybe even first)
to avoid processing any other middleware if we already know the request is for
`/favicon.ico`.

### express

```
var express = require('express')
var favicon = require('serve-favicon')
var path = require('path')

var app = express()
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))

// Add your routes here, etc.

app.listen(3000)
```

### connect

```
var connect = require('connect')
var favicon = require('serve-favicon')
var path = require('path')

var app = connect()
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))

// Add your middleware here, etc.

app.listen(3000)
```

### vanilla http server

This middleware can be used anywhere, even outside express/connect. It takes
`req`, `res`, and `callback`.

```
var http = require('http')
var favicon = require('serve-favicon')
var finalhandler = require('finalhandler')
var path = require('path')

var _favicon = favicon(path.join(__dirname, 'public', 'favicon.ico'))

var server = http.createServer(function onRequest (req, res) {
  var done = finalhandler(req, res)

  _favicon(req, res, function onNext (err) {
    if (err) return done(err)

    // continue to process the request here, etc.

    res.statusCode = 404
    res.end('oops')
  })
})

server.listen(3000)
```

## License

[MIT](https://expressjs.com/ko/resources/middleware/LICENSE)

---

# serve

참고

        This page was generated from the [serve-index README](https://github.com/expressjs/serve-index).

# serve-index

Serves pages that contain directory listings for a given path.

## Install

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[npm installcommand](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```
$ npm install serve-index
```

## API

```
var serveIndex = require('serve-index')
```

### serveIndex(path, options)

Returns middlware that serves an index of the directory in the given `path`.

The `path` is based off the `req.url` value, so a `req.url` of `'/some/dir`
with a `path` of `'public'` will look at `'public/some/dir'`. If you are using
something like `express`, you can change the URL “base” with `app.use` (see
the express example).

#### Options

Serve index accepts these properties in the options object.

##### filter

Apply this filter function to files. Defaults to `false`. The `filter` function
is called for each file, with the signature `filter(filename, index, files, dir)`
where `filename` is the name of the file, `index` is the array index, `files` is
the array of files and `dir` is the absolute path the file is located (and thus,
the directory the listing is for).

##### hidden

Display hidden (dot) files. Defaults to `false`.

##### icons

Display icons. Defaults to `false`.

##### stylesheet

Optional path to a CSS stylesheet. Defaults to a built-in stylesheet.

##### template

Optional path to an HTML template or a function that will render a HTML
string. Defaults to a built-in template.

When given a string, the string is used as a file path to load and then the
following tokens are replaced in templates:

- `{directory}` with the name of the directory.
- `{files}` with the HTML of an unordered list of file links.
- `{linked-path}` with the HTML of a link to the directory.
- `{style}` with the specified stylesheet and embedded images.

When given as a function, the function is called as `template(locals, callback)`
and it needs to invoke `callback(error, htmlString)`. The following are the
provided locals:

- `directory` is the directory being displayed (where `/` is the root).
- `displayIcons` is a Boolean for if icons should be rendered or not.
- `fileList` is a sorted array of files in the directory. The array contains
  objects with the following properties:
  - `name` is the relative name for the file.
  - `stat` is a `fs.Stats` object for the file.
- `path` is the full filesystem path to `directory`.
- `style` is the default stylesheet or the contents of the `stylesheet` option.
- `viewName` is the view name provided by the `view` option.

##### view

Display mode. `tiles` and `details` are available. Defaults to `tiles`.

## Examples

### Serve directory indexes with vanilla node.js http server

```
var finalhandler = require('finalhandler')
var http = require('http')
var serveIndex = require('serve-index')
var serveStatic = require('serve-static')

// Serve directory indexes for public/ftp folder (with icons)
var index = serveIndex('public/ftp', {'icons': true})

// Serve up public/ftp folder files
var serve = serveStatic('public/ftp')

// Create server
var server = http.createServer(function onRequest(req, res){
  var done = finalhandler(req, res)
  serve(req, res, function onNext(err) {
    if (err) return done(err)
    index(req, res, done)
  })
})

// Listen
server.listen(3000)
```

### Serve directory indexes with express

```
var express    = require('express')
var serveIndex = require('serve-index')

var app = express()

// Serve URLs like /ftp/thing as public/ftp/thing
// The express.static serves the file contents
// The serveIndex is this module serving the directory
app.use('/ftp', express.static('public/ftp'), serveIndex('public/ftp', {'icons': true}))

// Listen
app.listen(3000)
```

## License

[MIT](https://expressjs.com/ko/resources/middleware/LICENSE). The [Silk](http://www.famfamfam.com/lab/icons/silk/) icons
are created by/copyright of [FAMFAMFAM](http://www.famfamfam.com/).

---

# serve

참고

        This page was generated from the [serve-static README](https://github.com/expressjs/serve-static).

# serve-static

## Install

This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[npm installcommand](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):

```
$ npm install serve-static
```

## API

```
const serveStatic = require('serve-static')
```

### serveStatic(root, options)

Create a new middleware function to serve files from within a given root
directory. The file to serve will be determined by combining `req.url`
with the provided root directory. When a file is not found, instead of
sending a 404 response, this module will instead call `next()` to move on
to the next middleware, allowing for stacking and fall-backs.

#### Options

##### acceptRanges

Enable or disable accepting ranged requests, defaults to true.
Disabling this will not send `Accept-Ranges` and ignore the contents
of the `Range` request header.

##### cacheControl

Enable or disable setting `Cache-Control` response header, defaults to
true. Disabling this will ignore the `immutable` and `maxAge` options.

##### dotfiles

Set how “dotfiles” are treated when encountered. A dotfile is a file
or directory that begins with a dot (“.”). Note this check is done on
the path itself without checking if the path actually exists on the
disk. If `root` is specified, only the dotfiles above the root are
checked (i.e. the root itself can be within a dotfile when set
to “deny”).

- `'allow'` No special treatment for dotfiles.
- `'deny'` Deny a request for a dotfile and 403/`next()`.
- `'ignore'` Pretend like the dotfile does not exist and 404/`next()`.

The default value is `'ignore'`.

##### etag

Enable or disable etag generation, defaults to true.

##### extensions

Set file extension fallbacks. When set, if a file is not found, the given
extensions will be added to the file name and search for. The first that
exists will be served. Example: `['html', 'htm']`.

The default value is `false`.

##### fallthrough

Set the middleware to have client errors fall-through as just unhandled
requests, otherwise forward a client error. The difference is that client
errors like a bad request or a request to a non-existent file will cause
this middleware to simply `next()` to your next middleware when this value
is `true`. When this value is `false`, these errors (even 404s), will invoke
`next(err)`.

Typically `true` is desired such that multiple physical directories can be
mapped to the same web address or for routes to fill in non-existent files.

The value `false` can be used if this middleware is mounted at a path that
is designed to be strictly a single file system directory, which allows for
short-circuiting 404s for less overhead. This middleware will also reply to
all methods.

The default value is `true`.

##### immutable

Enable or disable the `immutable` directive in the `Cache-Control` response
header, defaults to `false`. If set to `true`, the `maxAge` option should
also be specified to enable caching. The `immutable` directive will prevent
supported clients from making conditional requests during the life of the
`maxAge` option to check if the file has changed.

##### index

By default this module will send “index.html” files in response to a request
on a directory. To disable this set `false` or to supply a new index pass a
string or an array in preferred order.

##### lastModified

Enable or disable `Last-Modified` header, defaults to true. Uses the file
system’s last modified value.

##### maxAge

Provide a max-age in milliseconds for http caching, defaults to 0. This
can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme)
module.

##### redirect

Redirect to trailing “/” when the pathname is a dir. Defaults to `true`.

##### setHeaders

Function to set custom headers on response. Alterations to the headers need to
occur synchronously. The function is called as `fn(res, path, stat)`, where
the arguments are:

- `res` the response object
- `path` the file path that is being sent
- `stat` the stat object of the file that is being sent

## Examples

### Serve files with vanilla node.js http server

```
const finalhandler = require('finalhandler')
const http = require('http')
const serveStatic = require('serve-static')

// Serve up public/ftp folder
const serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] })

// Create server
const server = http.createServer((req, res) => {
  serve(req, res, finalhandler(req, res))
})

// Listen
server.listen(3000)
```

### Serve all files as downloads

```
const contentDisposition = require('content-disposition')
const finalhandler = require('finalhandler')
const http = require('http')
const serveStatic = require('serve-static')

// Serve up public/ftp folder
const serve = serveStatic('public/ftp', {
  index: false,
  setHeaders: setHeaders
})

// Set header to force download
function setHeaders (res, path) {
  res.setHeader('Content-Disposition', contentDisposition(path))
}

// Create server
const server = http.createServer((req, res) => {
  serve(req, res, finalhandler(req, res))
})

// Listen
server.listen(3000)
```

### Serving using express

#### Simple

This is a simple example of using Express.

```
const express = require('express')
const serveStatic = require('serve-static')

const app = express()

app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] }))
app.listen(3000)
```

#### Multiple roots

This example shows a simple way to search through multiple directories.
Files are searched for in `public-optimized/` first, then `public/` second
as a fallback.

```
const express = require('express')
const path = require('path')
const serveStatic = require('serve-static')

const app = express()

app.use(serveStatic(path.join(__dirname, 'public-optimized')))
app.use(serveStatic(path.join(__dirname, 'public')))
app.listen(3000)
```

#### Different settings for paths

This example shows how to set a different max age depending on the served
file. In this example, HTML files are not cached, while everything else
is for 1 day.

```
const express = require('express')
const path = require('path')
const serveStatic = require('serve-static')

const app = express()

app.use(serveStatic(path.join(__dirname, 'public'), {
  maxAge: '1d',
  setHeaders: setCustomCacheControl
}))

app.listen(3000)

function setCustomCacheControl (res, file) {
  if (path.extname(file) === '.html') {
    // Custom Cache-Control for HTML files
    res.setHeader('Cache-Control', 'public, max-age=0')
  }
}
```

## License

[MIT](https://expressjs.com/ko/resources/middleware/LICENSE)
