简体   繁体   中英

Serve static files embedded in HTML boilerplate in Express

I have a directory of text files and serve them using Express. I currently serve the files using express.static

const express = require('express')
const app = express()
const port = 3000

var serveIndex = require('serve-index');

app.use(express.static(__dirname + "/public")) // Serve files
app.use(serveIndex(__dirname + '/public')); // Serve directories

app.listen(port, () => {})

However, I want to insert the content of the text file in between the <div> tags in this HTML boilerplate code and then serve this file.

<!DOCTYPE html>
<html>
<head></head>
<body>

<div>
    CONTENT GOES HERE
</div>

</body>
</html>

I have not been able to find a way to edit the static files before serving them though. Would I need to modify the code in the serve-static module?

The better approach for this is to use the template engine...

I would recommend using handlebars because that is easy enough.

But still if you want to do manually you will have to read the file using filesystem and then return it...

var fs = require('fs');

app.get('/file1', function(req, res, next) {
    var file = fs.readFileSync('./public/path_to_text_file.txt', 'utf8')
    res.send(`
        <!DOCTYPE html>
        <html>
         <head></head>
         <body>

           <div>
             ${file.toString()}
           </div>

         </body>
        </html>

    `);
})

If you want to do this for all the text files at once then you can create a dynamic route like below.

const path = require("path");
const fs = require("fs");

app.get('/files/:file_name', function(req, res, next) {
    // assemble the file path
    const file_path = path.join("./public/files", req.params.file_name);
    // you can make sure the file name or type here (validations)

    
    if(fs.existsSync(file_path)){
        // get the file content
        const file = fs.readFileSync(file_path, 'utf8')
        res.send(`
            <!DOCTYPE html>
            <html>
                <head></head>
            <body>
               <div>
                    ${file.toString()}
               </div>
            </body>
            </html>
        `);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM