https://github.com/bfncs/string-replace-middleware
String Replace Middleware for Express
https://github.com/bfncs/string-replace-middleware
express middleware
Last synced: 2 months ago
JSON representation
String Replace Middleware for Express
- Host: GitHub
- URL: https://github.com/bfncs/string-replace-middleware
- Owner: bfncs
- License: mit
- Created: 2016-09-15T21:36:24.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2024-06-18T07:33:37.000Z (almost 2 years ago)
- Last Synced: 2025-09-20T14:23:27.430Z (9 months ago)
- Topics: express, middleware
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/string-replace-middleware
- Size: 549 KB
- Stars: 8
- Watchers: 2
- Forks: 5
- Open Issues: 4
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# String Replace Middleware
A middleware for [Express](http://expressjs.com/) that allows for stream-based string replacement before sending responses.
## Installation
Install in your Express project using:
```
npm install --save string-replace-middleware
```
## Usage
After installing, you can add it as a middleware to your project and hand over a map of replacements. To replace every occurence of `foo` with `bar`.
```javascript
const express = require('express');
const { stringReplace } = require('string-replace-middleware');
const app = express();
app.use(stringReplace({
'foo': 'bar',
}));
app.listen(3000);
```
Use it to serve static files with replacements like in this example:
```javascript
const express = require('express');
const serveStatic = require('serve-static');
const { stringReplace } = require('string-replace-middleware');
const app = express();
app.use(stringReplace({
'foo': 'bar',
}));
app.use(serveStatic('public'));
app.listen(3000);
```
### Dynamic replacements
You might also replace dynamically with access to all the content of [Request](https://expressjs.com/de/api.html#req) and [Response](https://expressjs.com/de/api.html#res):
```
stringReplace({
'$host' => (req, res) => 'your host ' + req.hostname
});
```
## Configuration
The Content-Type header of responses is checked against a regex before modification. The regex is configurable by passing in
an options object like this:
```javascript
const options = {
contentTypeFilterRegexp: /^text\/|^application\/json$|^application\/xml$/,
}
app.use(stringReplace({
'foo': 'bar',
}, options));
```
The default regex is `/^text\/|^application\/json$|^application\/xml$/`, which will match `text/*`, `application/json`, and `application/xml`. Any response with a Content-Type header that doesn't match the regex is ignored and passed-through without modification.
Also any response without a Content-Type header is ignored and passed-through without any modification.