First, you will need the Transform
class from the stream
node library, so add the following to the beginning of your code:
const Transform = require("stream").Transform
Then replace
app.get("/", (req, res) => {
res.sendFile("index.html")
})
with the following:
app.get("/", (req, res) => {
const replacementTransform = new Transform()
replacementTransform._transform = function(data, encoding, done) {
const str = data.toString().replace('anything you want to replace', `whatever you want to replace with`)
this.push(str)
done()
}
res.write('<!-- Begin stream -->
');
let stream = fs.createReadStream('./index.html')
stream.pipe(replacementTransform)
.on('end', () => {
res.write('
<!-- End stream -->')
}).pipe(res)
})
This will replace any string sequence in your HTML document with anything else you want. The most useful way to use this is to fill the inside of an HTML element by replacing <p id="empty"></p>
with <p id="empty">something</p>
.
For larger files, it may be convenient to pipe the file data in chunks instead of as one big piece, which is where a useful library called new-line
comes in. Simply install it through npm, require it in your file, and replace the current output stream with
res.write('<!-- Begin stream -->
');
let stream = fs.createReadStream('./index.html')
stream.pipe(new-line())
.pipe(replacementTransform)
.on('end', () => {
res.write('
<!-- End stream -->')
}).pipe(res)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…