Home > Net >  Serve static files embedded in HTML boilerplate in Express
Serve static files embedded in HTML boilerplate in Express

Time:01-01

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?

CodePudding user response:

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>
        `);
    }
});
  • Related