Skip to content
Advertisement

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`
    );
  }
}

Advertisement

Answer

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`);
      }
    }
  });
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement