Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

node.js - Edit HTML documents before they are sent from an express server

This solution is useful when you have very few things that you want to replace on your page, and still want a way to update the page without any HTTP requests or frontend workarounds.

question from:https://stackoverflow.com/questions/66055531/edit-html-documents-before-they-are-sent-from-an-express-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...