Home>

I want to implement a text file that adds objects to an array.
A specific example is

[
 {
   "private key": private_key,
   "public key": public_key
  }
 {
   "private key": private_key,
   "public key": public_key
  }
  :
]
Error message

But the actual text file output is

{"private key": 4jt4q ....., "public key": 54321f4ddg .....}


Then, when the file is written, the contents of the dictionary are updated, and another dictionary cannot be added.

Applicable source code
const bitcoinjs = require ("bitcoinjs-lib")
const crypto = require ("crypto")
const base58Check = require ("bs58check")
const fs = require ("fs")
let random1 = crypto.randomBytes (32)
let ECPair = bitcoinjs.ECPair.fromPrivateKey (random1, {compressed: false})
let private_key = ECPair.privateKey.toString ("hex")
let public_key = ECPair.publicKey.toString ("hex")
function Key_file (private_key, public_key) {
    const key_list = {
        "Private Key": private_key,
        "Public Key": public_key,
    }
    const jsonString = JSON.stringify (key_list)
    const jsonBuffer = Buffer.from (jsonString, "utf8")
    fs.writeFileSync ("key.txt", jsonBuffer)

}
Key_file (private_key, public_key)

Dictionaries were created again after fs.writeFileSync ("key.txt", jsonBuffer), and fs.readFileSync was added.

  • Answer # 1

      

    When I write a file, the contents of the dictionary are updated, and another dictionary cannot be added.

    Because it's always overwritten and saved.
    The basic file operation is "read, write, save".

    // NodeJS
    const fs = require ("fs")
    const file = "key.txt";
    function loadJson (filepath) {
      let jsonText;
      if (fs.statSync (filepath) .isFile ()) {
        jsonText = fs.readFileSync (filepath, "utf8");
      }
      return jsonText? JSON.parse (jsonText): "";
    }
    function saveJson (filepath, json) {
      let jsonText = JSON.stringify (json);
      fs.writeFileSync (filepath, jsonText, "utf8");
    }
    function Key_file (private_key, public_key) {
      // Read: Read the file and get the contents
      let ary = loadJson (file) || [];
      // Write: Update content
      ary.push ({/ * omitted * /});
      // Save: Overwrite update contents
      saveJson (file, ary);
    }


    Note) The above code is expressed by the following synchronization function of NodeJS.

    fs.statSync ()

    fs.readFileSync ()

    fs.writeFileSync ()

    If you want performance, you need to think more.

    Think about other logic

    DB instead of file.

    Introduce RAM drive to speed up and perform regular backup.
    (It is easy to lose data if a part of volatile main memory is made into a drive)

    etc

  • Answer # 2

    fs.readFileto retrieve the file
    I think that it can be done by adding (push) new data to the acquired data and saving it