als-send-file
Version:
file serving with advanced options for caching, headers, and error handling, compatible with Express middleware.
96 lines (69 loc) • 3.92 kB
Markdown
# als-send-file
`als-send-file` is a Node.js library designed to facilitate file serving with custom options to easily serve files with detailed control over caching, headers, and error handling. It can be used as middleware in Express.js and similar frameworks.
## Installation
Install the package via npm:
```bash
npm install als-send-file
```
And import:
```js
const { fileHandler, sendFileMw } = require('als-send-file');
```
## Middleware usage `sendFileMw`
The `sendFileMw` function creates middleware that adds a `sendFile` method to the response object (`res.sendFile`). This method can be used within your route handlers to serve files with specific options.
### Parameters
- `root`: The root directory from which files will be served. Must be a valid string path.
- `httpErrorHandler`: A function to handle HTTP errors. It should take three arguments: `(res, statusCode, message)`.
- `$options`: An object specifying default options for file serving. These options are merged with any options specified at the time of calling `res.sendFile`.
The middleware validates these parameters and throws an error if validation fails.
### Usage of `res.sendFile`
```javascript
const express = require('express');
const { sendFileMw } = require('als-send-file');
const app = express();
app.use(sendFileMw(__dirname, (res, code, msg) => {
res.status(code).send(msg);
}));
app.get('/file/:name', (req, res) => {
res.sendFile(req.params.name, { download: true, noCache: true });
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
```
## Function `fileHandler` usage
`fileHandler` directly handles file serving with detailed options.
### Parameters and Validation
- `req`: The HTTP request object.
- `res`: The HTTP response object.
- `filePath`: Path to the file to be served.
- `options`: Object containing options that affect headers and handling behaviors:
- `download` (Boolean, default: false): Sets `Content-Disposition` to `attachment` for downloads or `inline` to open in the browser.
- `charset` (String, optional): Adds charset to `Content-Type`.
- `etag` (Boolean, default: true): Adds `Last-Modified` and `ETag` for client-side caching.
- `maxAge` (Number, optional): Specifies the maximum amount of time (in seconds) that the resource is considered fresh.
- `noCache` (Boolean, default: false): Requires that all copies of the response be revalidated with the server before use.
- `noStore` (Boolean, default: false): Prohibits any caching of the response.
- `public` (String, optional): Indicates where the response may be cached (in public proxies or only in the user’s browser). Defaults to `public` if any other value is passed.
- `httpErrorHandler`: A function to handle HTTP errors. It should take three arguments: `(res, statusCode, message)`.
### Example Usage
```javascript
const http = require('http');
const { fileHandler } = require('als-send-file');
const server = http.createServer((req, res) => {
const httpErrHandler = (res, code, msg) => {
res.status(code).send(msg);
}
fileHandler(req, res, 'path/to/file.txt', { download: true }, httpErrHandler);
});
server.listen(3000);
```
## Expected Results
When using `fileHandler`, the function sets appropriate HTTP headers based on the options provided and handles file serving. The possible HTTP statuses returned include:
- `200 OK`: File served successfully.
- `404 Not Found`: File not found.
- `500 Internal Server Error`: Errors during file serving.
- `304 Not Modified`: File not modified (ETag matches).
- `206 Partial Content`: Partial file data returned for range requests.
- `416 Range Not Satisfiable`: Invalid range requested.
The function returns a promise, facilitating advanced handling and integration within asynchronous functions.