简体   繁体   中英

String interpolation on static files served by Nodejs

Hi I have Nodejs server which serves static resource at /assets/meta-info.json which contains:

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

The problem is: How to replace ${ENV_NAME} with corresponding system environment variable?

You can probably save it as /assets/meta-info.js You can import 'dotenv' npm library.

In assets/meta-info.js

 require('dotenv').config();

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

Have a.env file (no extension). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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