string-replace-middleware
Advanced tools
Comparing version 0.0.1 to 1.0.0
const hijackResponse = require('hijackresponse'); | ||
const stringReplaceStream = require('./stringReplaceStream'); | ||
module.exports = (replacements) => (req, res, next) => { | ||
const defaultOptions = { | ||
contentTypeFilterRegexp: /^text\/|^application\/json$|^application\/xml$/, | ||
} | ||
module.exports = (replacements, options = defaultOptions ) => (req, res, next) => { | ||
hijackResponse(res, function (err, res) { | ||
if (err) { | ||
res.unhijack(); // Make the original res object work again | ||
return next(err); | ||
const contentType = res.get('content-type'); | ||
if (options.contentTypeFilterRegexp.test(contentType)) { | ||
if (err) { | ||
res.unhijack(); // Make the original res object work again | ||
return next(err); | ||
} | ||
res.removeHeader('Content-Length'); | ||
res | ||
.pipe(stringReplaceStream(replacements)) | ||
.pipe(res); | ||
} else { | ||
return res.unhijack(); | ||
} | ||
res.removeHeader('Content-Length'); | ||
res | ||
.pipe(stringReplaceStream(replacements)) | ||
.pipe(res); | ||
}); | ||
next(); | ||
}; |
{ | ||
"name": "string-replace-middleware", | ||
"version": "0.0.1", | ||
"version": "1.0.0", | ||
"description": "Express middleware to replace strings in response stream on the fly", | ||
@@ -5,0 +5,0 @@ "author": "Marc Loehe <marc@marcloehe.de>", |
@@ -11,3 +11,3 @@ # String Replace Middleware | ||
npm install --save string-replace-middleware | ||
```` | ||
``` | ||
@@ -46,2 +46,21 @@ ## Usage | ||
app.listen(3000); | ||
``` | ||
``` | ||
## 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. |
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
4853
76
1
64
4