Cách nodejs đọc và ghi tệp .env?

Dec 11 2020

Làm thế nào để đọc và ghi tệp env?

Tệp gốc :

# I am a note ...
key1=value1

key2=value2
   # I am a note ...

Tôi cần một chức năng setEnv(key, value).

chạy setEnv('key1', 'value2'), Hãy để nó trở thành :

# I am a note ...
key1=value2

key2=value2
   # I am a note ...

Làm thế nào tôi có thể đạt được nó?

Trả lời

2 GribeshDhakal Dec 11 2020 at 21:24

Hãy bắt đầu bằng cách tạo dự án mới.

mkdir folder_name
cd folder_name
npm init

Sau đó, trong thư mục dự án của bạn, hãy cài đặt 'envfile' và 'dotenv'. Lệnh cài đặt envfile là

npm install envfile --save

Tương tự cài đặt dotenv

npm install dotenv --save

gói dotenv trực tiếp đọc tệp .env gói tệp envfile được sử dụng để phân tích cú pháp và xâu chuỗi tệp theo yêu cầu. Tạo .envtệp trong thư mục dự án với thông tin chi tiết của bạn.

# I am a note ...
key1=value1

key2=value2
   # I am a note ...

Tạo một tệp mới với filename.js

Sau đó, để lấy và thiết lập các biến env, bạn có thể sử dụng mã sau.

const fs = require('fs');
require('dotenv').config()
const {
    parse,
    stringify
} = require('envfile');
const pathToenvFile = '.env';

/**
 * 
 * @param {string} key 
 * //Function to get value from env
 */
function getEnv(key) {
    console.log("Getting value of " + key);
    console.log(process.env[key]);
}
//Calling the function getEnv
getEnv("key1");


/**
 * 
 * @param {string} key 
 * @param {string} value 
 * //Function to set environment variables.
 */
function setEnv(key, value) {
    fs.readFile(pathToenvFile, 'utf8', function (err, data) {
        if (err) {
            return console.log(err);
        }
        var result = parse(data);
        result[key] = value;
        console.log(result);
        fs.writeFile(pathToenvFile, stringify(result), function (err) {
            if (err) {
                return console.log(err);
            }
            console.log("File Saved"); // Can be commented or deleted
        })

    });
}
//Calling the function setEnv
setEnv('key1', 'value2');

Sau khi chạy tệp của bạn bằng cách sử dụng

node filename.js

Bạn có thể nhận được đầu ra mong muốn của bạn.

Tệp .env ban đầu

# I am a note ...
key1=value1

key2=value2
   # I am a note ...

Sau khi chạy chương trình

key1=value2
key2=value2

Có, bình luận của bạn sẽ bị xóa.

1 plc-dev Dec 11 2020 at 20:05

Bạn có thể sử dụng envfilemô-đun như được mô tả ở đây .

const fs = require('fs');
const envfile = require('envfile');
const envPath = 'pathToEnvFile/.env';
let parsedFile = envfile.parseFileSync(envPath);
parsedFile.NEW_VAR = 'newVariableValue';
fs.writeFileSync(envPath, envfile.stringifySync(parsedFile));
ebyte Dec 11 2020 at 20:17

Một cái gì đó như thế này :

function setEnv(envText, key, value) {
  if (!envText) {
    return;
  }
  const rp = new RegExp(`${key}=(.*?)\\s`); let result = envText.replace(rp, (m, $1) => {
    return m.replace($1, value); }); if (!rp.test(result)) { result += `\n${key}=${value}`;
  }
  return result;
}

console.log(
  setEnv(
    `# I am a note ...
  key1=value1
  
  key2=value2
     # I am a note ...`,
    'key1',
    'value2',
  ),
);

Nhưng điều này không hoạt động:

setEnv(
    `# I am a note ...
  key1=value1
  
  key2=value2`,
    'key2',
    'value1',
  )
setEnv(
    `# I am a note ...
  key1key2=value1
  
  key2=value2`,
    'key2',
    '2222',
  )