javascript - Nodejs 提供的静态文件的字符串插值
问题描述
嗨,我有 Nodejs 服务器,它提供静态资源,/assets/meta-info.json
其中包含:
{
"environmentName": "${ENV_NAME}"
}
问题是:如何替换${ENV_NAME}
成对应的系统环境变量?
解决方案
You could modify the file when the server starts and request that modified file (or you can rename the original file and keep serve original modified file) something like modifying the original file during runtime (which is not advisable as you will modifying the same file again and again) =>
const fs = require('fs');
const path = require('path');
const express = require('express');
const app = express();
app.get('/', (req, res) => {
let fileBuffer = fs.readFileSync('./manifest.json', 'utf-8');
fileBuffer = fileBuffer.replace('${ENV_NAME}', process.env.NODE_ENV);
fs.writeFileSync('./temp.json', fileBuffer);
res.sendFile(path.join(__dirname, './temp.json'));
});
app.listen(4000, () => {
console.log('listening and working');
});
Instead modify it once and send the modified copy.
let fileBuffer = fs.readFileSync('./manifest.json', 'utf-8');
fileBuffer = fileBuffer.replace('${ENV_NAME}', process.env.NODE_ENV);
fs.writeFileSync('./temp.json', fileBuffer);
const app = express();
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, './temp.json'));
});
Now if you are using something like express.serveStatic
, then I would create a backup copy of file and modify the original file in place.
推荐阅读
- javascript - getJSON 在按钮单击时不起作用,但在按回车键时起作用
- python - 使用 newthon-raphson 时出现此错误:在 double_scalars 中遇到无效值
- python - PySNMP 如何处理具有读取创建权限的表?
- jenkins-pipeline - 是否可以将 Jenkins 管道节点值设置为参数?
- typescript - 映射对象分配:`string` 不可分配给`key in N`
- ibm-mq - LDAPCONN (INACTIVE):如何成功评估 ldapconn 非活动错误的原因?
- firebase - Admob 中没有“链接到 Firebase”选项
- php - 如何使用 ajax(一个文件)从 php 获取响应数据?
- javascript - 为什么在 componentDidUpdate 中比较数组不会导致无限循环?
- node.js - 需要有一个函数来处理数据库中的所有 CRUD 操作