restream
yarn add -E restream
Regular expression detection implemented as a transform Steam and regex-based buffer replacement stream to replace streamed data on-the-fly.
import restream, { replaceStream } from 'restream'
Table of Contents
restream(regex: RegExp) => Transform
Create a transform stream which will buffer incoming data and push regex results
when matches can be made, i.e. when regex.exec
returns non-null value. You will probably want to
set the g
flag on regexes most of the time.
import restream from 'restream'
import { createReadable, createWritable } from './lib'
(async () => {
try {
const rs = createReadable('test-string-{12345}-{67890}')
const stream = restream(/{(\d+)}/g)
rs.pipe(stream)
const { data, ws } = createWritable()
stream.pipe(ws)
ws.once('finish', () => {
console.log(data)
})
} catch (err) {
console.error(err)
}
})()
[ [ '{12345}',
'12345',
index: 12,
input: 'test-string-{12345}-{67890}' ],
[ '{67890}',
'67890',
index: 20,
input: 'test-string-{12345}-{67890}' ] ]
replaceStream({re:RegExp, replacement:string }[]) => Transform
Creates a Transform
stream which will make data available
when an incoming chunk has been updated according to the regex
input, which can
be either a single regex object ({ re: /regex/, replacement: 'hello-world' }
),
or an array of such objects. A replacement
can be either a string, or a function,
which will be called by str.replace
import Catchment from 'catchment'
import { replaceStream } from 'restream'
import { createReadable } from './lib'
(async () => {
try {
const stream = replaceStream([{
re: /{{ user }}/,
replacement: 'fred',
}, {
re: /{{ name }}/g,
replacement: 'Fred',
}, {
re: /{{ stars }}/,
replacement: '5',
}])
const rs = createReadable('Hello {{ name }}, your username is {{ user }} and you have {{ stars }} stars')
rs.pipe(stream)
const { promise } = new Catchment({
rs: stream,
})
const res = await promise
console.log(res)
} catch (err) {
console.error(err)
}
})()
Output:
Hello Fred, your username is fred and you have 5 stars
replaceStream({re:RegExp, replacement: function(match, ...params) }[]) => Transform
You can replace matches using a function. See MDN for more documentation.
import { replaceStream } from '../src'
import Catchment from 'catchment'
import { createReadable } from './lib'
(async () => {
try {
const stream = replaceStream([{
re: /__(\S+)__/g,
replacement(match, p1) {
return `<em>${p1}</em>`
},
}])
const rs = createReadable('Hello __Fred__, your username is __fred__ and you have __5__ stars.')
rs.pipe(stream)
const { promise } = new Catchment({
rs: stream,
})
const res = await promise
console.log(res)
} catch (err) {
console.error(err)
}
})()
Output:
Hello <em>Fred</em>, your username is <em>fred</em> and you have <em>5</em> stars
(c) Art Deco Code 2018