Joey Yi Zhao
Joey Yi Zhao

Reputation: 42480

How to modify static file content with express.static?

I am using express.static to serve some static files. I want to modify some files content before return to the client. Below is the source code for static resources under /public path.

app.use('/public', express.static(path.join(__dirname, 'public')))

There are some html files under the public directory and I want to modify the html files before responsing to the client.

How can I do that with static? I know I can add customized middlewares but not sure how. Is there a middleware pattern I can use?

Upvotes: 4

Views: 4987

Answers (1)

jfriend00
jfriend00

Reputation: 707308

You don't use express.static() for files you want to modify - that's not what it does.

The USUAL way to modify HTML files before serving them is to use a template system. There are dozens of template systems for the Express eco-system (such as EJS, Jade, Handlebars, etc...) that are specifically designed to solve this problem. You use the template's language to specify where in the template you want content inserted.

If you really want to write your own system to modify content before sending it, you can just load the file yourself, make whatever modifications you want and then send it.

app.get("/public/somefile", function(req, res) {
    fs.readFile(path.join(__dirname, 'public', 'somefile'), function(err, data) {
        if (err) {
            res.sendStatus(404);
        } else {
            // modify the data here, then send it
            res.send(data);
        }
    });
});

// put express.static after your other routes that serve from the public
// directory so those other routes are matched first
app.use('/public', express.static(path.join(__dirname, 'public')));

Upvotes: 5

Related Questions