简体   繁体   English

Nodejs 提供的 static 文件上的字符串插值

[英]String interpolation on static files served by Nodejs

Hi I have Nodejs server which serves static resource at /assets/meta-info.json which contains:嗨,我有 Nodejs 服务器,它在/assets/meta-info.json提供static 资源,其中包含:

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

The problem is: How to replace ${ENV_NAME} with corresponding system environment variable?问题是:如何将${ENV_NAME}替换为相应的系统环境变量?

You can probably save it as /assets/meta-info.js You can import 'dotenv' npm library.您可以将其保存为 /assets/meta-info.js 您可以导入 'dotenv' npm 库。

In assets/meta-info.js在资产/meta-info.js

 require('dotenv').config();

    module.exports = {
      "environmentName": process.env.ENV_NAME
    }

Have a.env file (no extension).有一个 .env 文件(无扩展名)。 have line below:下面有一行:

ENV_NAME=prod

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.现在,如果您使用的是express.serveStatic之类的东西,那么我将创建文件的备份副本并就地修改原始文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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