Рубрики
Без рубрики

Написание сценария настройки ENV

На днях я решил сделать сценарий настройки для траты. Money. Если вы не знаете, что watherof.mon … с меткой узла, javascript, env, setup.

На днях я решил сделать сценарий настройки для траты. Money. Если вы не знаете, что такое watherof.money, проверьте это на dev.wasteof.money! Для начала я хотел написать .env. Сценарий, который я написал для этого, просто написал .env с использованием fs.

const fs = require("fs");
fs.writeFile(".env", `DB_URL=`, "utf8", function () {
  console.log("Got it!");
});

Затем я хотел, чтобы пользователь смог вставить входные данные. Для этого я использовал пакет подсказок из NPM. Мой код теперь выглядел так:

const prompts = require("prompts");
const fs = require("fs");
(async () => {
  const response = await prompts([
    {
      type: "text",
      name: "url",
      message:
        "What is your MongoDB URL? (If you are using MongoDB Atlas, you can keep the <> values)",
    },
    {
      type: "text",
      name: "port",
      message: "What port should the site run on?",
      initial: 8080,
    }
  ]);

  fs.writeFile(
    ".env",
    `DB_URL=${response.url
      \nLISTEN_PORT=${response.port}`,
    "utf8",
    function () {
      console.log("Your settings have been written to .env!");
      console.log("Run npm run serve to start the server or npm run dev to start it with nodemon.");
    }
  );
})();

На данный момент код работал, но он все еще не удовлетворял меня. Я хотел, чтобы пользователь мог ввести пароль и выключился со значением от MongoDB Atlas.

Я решил, что он также должен спросить пользователя, используют ли он Local или Atlas. Моя финальная версия выглядела так.

const prompts = require("prompts");
const fs = require("fs");
require("dotenv").config();
const port = process.env.LISTEN_PORT || 8080;
const url = process.env.DB_URL || "localhost/social";

(async () => {
  const response = await prompts([
    {
      type: "text",
      name: "url",
      message: "What is your MongoDB URL? (If you are using MongoDB Atlas, you can keep the <> values)",
      initial: url,
    },
    {
      type: "select",
      name: "value",
      message: "Pick a hosting type",
      choices: [
        {
          title: "MongoDB Atlas",
          description: "MongoDB Atlas cloud hosting",
          value: "atlas",
        },
        {
          title: "Local MongoDB",
          value: "local",
          description: "A local MongoDB instance",
        },
      ],
    },
    {
      type: (prev) => (prev == "atlas" ? "password" : null),
      name: "password",
      message: "What is your MongoDB Password?",
    },
    {
      type: "text",
      name: "port",
      message: "What port should the site run on?",
      initial: port,
    },
  ]);

  fs.writeFile(
    ".env",
    `DB_URL=${response.url.replace("", response.password).replace("", "social")}\nLISTEN_PORT=${
      response.port
    }`,
    "utf8",
    function () {
      console.log("Your settings have been written to .env!");
      console.log("Run npm run serve to start the server or npm run dev to start it with nodemon.");
    }
  );
})();

Оригинал: “https://dev.to/grahamsh/writing-an-env-setup-script-436a”