Search code examples
node.jsdotenv

How to programmatically write a value to a variable in my .env file?


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?


Solution

  • 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().