Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

481
Views
JavaScript, how to run a piece of code only once?

I am saving my .env content dynamically from the AWS secrets manager, but I want to save all values just once the server starts. What should be the approach?

I am using TypeScript:

getSecrets("key").then((keys: any) => {
 const originalKeys = JSON.parse(keys);
 for (const key in originalKeys) {
  if (originalKeys.hasOwnProperty(key)) {
    appendFileSync(
      __dirname + "/.env",
      `${key}='${originalKeys[key]}'\n`
    );
  }
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You could use a boolean to remember whether the code has been executed or not. Something like this:

let excecuted = false;
if (!excecuted) {
  excecuted = true;
  getSecrets("key").then((keys: any) => {
    const originalKeys = JSON.parse(keys);
    for (const key in originalKeys) {
      if (originalKeys.hasOwnProperty(key)) {
        appendFileSync(__dirname + "/.env", `${key}='${originalKeys[key]}'\n`);
      }
    }
  });
}
about 4 years ago · Juan Pablo Isaza Report

0

I am saving my .env content dynamically from the AWS secrets manager.

Why do you want to save them in .env? You can save them in the config object and you can reuse them where ever you need them.

const AWS = require('aws-sdk'); 

class SecretsManager {
    
    let #config = null;
    async #getSecret (secretName, region){
        const config = { region : region }
        var secret, decodedBinarySecret;
        let secretsManager = new AWS.SecretsManager(config);
        try {
            let secretValue = await secretsManager.getSecretValue({SecretId: secretName}).promise();
            if ('SecretString' in secretValue) {
                return secret = secretValue.SecretString;
            } else {
                let buff = new Buffer(secretValue.SecretBinary, 'base64');
                return decodedBinarySecret = buff.toString('ascii');
            }
        } catch (err) {
            if (err.code === 'DecryptionFailureException')
                // Secrets Manager can't decrypt the protected secret text using the provided KMS key.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw err;
            else if (err.code === 'InternalServiceErrorException')
                // An error occurred on the server side.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw err;
            else if (err.code === 'InvalidParameterException')
                // You provided an invalid value for a parameter.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw err;
            else if (err.code === 'InvalidRequestException')
                // You provided a parameter value that is not valid for the current state of the resource.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw err;
            else if (err.code === 'ResourceNotFoundException')
                // We can't find the resource that you asked for.
                // Deal with the exception here, and/or rethrow at your discretion.
                throw err;
        }
    } 

    static async getSecretValues() {
        const secretName = '<secretsName>';
        const region = '<Region>';
       try {
       if (!this.#config) { 
          return this.#config;
       } else {
          this.#config = await this.#getSecret(secretName, region);
       }
      } catch (e) {
        console.log(e);
      }
    }
}
module.exports = SecretsManager;

In your files you can use this:

const SecretsManager = require('./SecretsManager.js');

const secret = SecretsManager.getSecretValues();

You can check here for more details.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!