0

I have a Node.JS v8.11.1 app running on an Ubuntu 14.04 LTS box. The app serves up AngularJS Javascript files and the HTML files that use them. I want to have a string value injected into one of the Javascript files that is sourced from an environment variable on the server, before I send the Javascript file to the client (i.e. - user's browser).

I know I can access the environment variables on the server side using "process.env.{environment.variable name}". What I need to know is how to take that value, inject it into my Javascript file so that when the Javascript file executes on the client side it has the desired string in its code. For example:

Environment variable on server side:

SOME_ENV_VAR=12345

Javascript statement in source file on server side:

var someVar = "REPLACE ME AT RUNTIME";

Javascript statement in source file by the time it reaches the client side:

var someVar = "12345";

How should I do this? Should I use a templating engine like Jade/Pug? Is that overkill?

Robert Oschler
  • 14,153
  • 18
  • 94
  • 227
  • 1
    You said it is an angularjs app. So it is as simple as placing the code above in a script tag in your `index.html` file. You can use the NodeJS `fs` api to search and replace that simple string in `index.html` prior to it being served. If you are using Express, this could be done in a middleware. – Randy Casburn Apr 05 '18 at 05:19

2 Answers2

1
   app.get("some-script.js", (req, res) => {
     fs.readFile("some-script.js", (err, file) => {
        res.send(file.replace("12345", process.env.sth));
    });
  });

Just replace it when you send it. Alternatively, you could modify the file on startup:

   fs.writeFileSync("some-script.js", fs.readFileSync("some-script.js").replace("12345", process.env.arg));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

You can solve your issue by Task runner like Grunt or Gulp. Or also you can use Webpack to bundle your file before serve. This node module will helpful to you. https://www.npmjs.com/package/grunt-contrib-copy

    copy: {
    main: {
        src: 'src/file.js',
        dest: 'src/file.min.js',
        options: {
        process: function (content, srcpath) {
            return content.replace('REPLACE ME AT RUNTIME',SOME_ENV_VAR);
        },
        },
    },
    },
Munir Khakhi
  • 123
  • 1
  • 7