0

So for my Node.js app I created a seed script that can be called from the command line. This creates a user and a password based on a JWT secret. When running the script I want the secret to be a custom generated string and write it to the APP_SECRET variable in my .env file. Is there any way to programmatically fill the variable with this custom string in the .env file?

Djurdjen
  • 273
  • 2
  • 10
  • 1
    What have you tried so far? Read the file, replace whatever value is after APP_SECRET= and write the file back to the file system. Another option is to use a .env template file, or maybe just append to the end of the file the new value, etc. – rodrigoap Dec 05 '19 at 13:50

1 Answers1

4

So, you need do 2 things: generate random string and write it to your .env file.

  1. For generating random string use npm package or your handmade generator based on node crypto module.
  2. Than use fs nodule to write variable to file. For example,

    fs.appendFileSync('.env', 'APP_SECRET=var');

    or

    fs.appendFile('.env', 'APP_SECRET=var', function (err) {
       if (err) throw err;
    });

However, this would append string to file. If you want replace ENV variable every time, use fs.writefile().

Pyroarsonist
  • 186
  • 1
  • 6