Pennf0lio
Pennf0lio

Reputation: 3896

Trying to read and write on PhantomJS

I'm trying to read and write on a JSON file but I'm a bit stuck in implementing it. I'm trying to append new datas in a JSON file as I iterate on more records.

// scripts.js

var jsonFile    = '../data/data.json';
var data        = { "id": 0, "animal": "Dog" }, { "id": 1, "animal": "Cat" };

var readData    = fs.read( jsonFile );

readData = readData.push( data );

fs.write( jsonFile, readData, 'a' );

--

What i'm trying to achieve

data.json

[]

data.json - 1st iteration

[
    { "id": 0, "animal": "Dog" }, 
    { "id": 1, "animal": "Cat" }
]

data.json - 2nd iteration

[
    { "id": 0, "animal": "Dog" }, 
    { "id": 1, "animal": "Cat" },
    { "id": 2, "animal": "Owl" },
    { "id": 3, "animal": "Bat" }
]

Upvotes: 0

Views: 64

Answers (1)

Jason Livesay
Jason Livesay

Reputation: 6377

Put [] in the file 'data.json' before running this.

const fs = require('fs-promise');

async function addRecord(jsonFile, row) {
  const json = await fs.readFile(jsonFile,'utf8');
  const rows = JSON.parse(json);
  rows.push(row);
  await fs.writeFile(jsonFile, JSON.stringify(rows));
}

async function test1() {
  const jsonFile = 'data.json';
  await addRecord(jsonFile, { "id": 0, "animal": "Dog" });
  await addRecord(jsonFile, { "id": 1, "animal": "Cat" });
}

test1().catch(console.error);

Upvotes: 2

Related Questions