【问题标题】:Serve static files embedded in HTML boilerplate in Express在 Express 中提供嵌入在 HTML 样板中的静态文件
【发布时间】:2021-12-28 15:22:31
【问题描述】:

我有一个文本文件目录,并使用 Express 为它们提供服务。我目前使用 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, () => {})

但是,我想在此 HTML 样板代码中的 <div> 标记之间插入文本文件的内容,然后提供此文件。

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

<div>
    CONTENT GOES HERE
</div>

</body>
</html>

我还没有找到在提供静态文件之前编辑它们的方法。我需要修改 serve-static 模块中的代码吗?

【问题讨论】:

标签: javascript html node.js express


【解决方案1】:

更好的方法是使用模板引擎...

我建议使用车把,因为这很容易。

但是,如果您想手动执行,则必须使用文件系统读取文件,然后将其返回...

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>

    `);
})

如果您想一次对所有文本文件执行此操作,则可以创建如下所示的动态路由。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多