首页 > 解决方案 > Nodejs 提供的静态文件的字符串插值

问题描述

嗨,我有 Nodejs 服务器,它提供静态资源/assets/meta-info.json其中包含:

{
  "environmentName": "${ENV_NAME}"
}

问题是:如何替换${ENV_NAME}成对应的系统环境变量?

标签: javascriptnode.jsassetsstring-interpolation

解决方案


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.


推荐阅读