Write data to json file using Protractor

5.3k Views Asked by At

I have a code to read data from json file using protractor and it works properly. For that I created json file in project folder. Then included that test data file in test scripts pages by using 'var data = require('../testdata.json')"

I am reading the file in follwing way: Example:

testdata.json file:

{ "Name":"Json Test Data", "Purpose":"Storing test data" }

Usage: "data.Name" retrieved value is"Json Test Data" "data.Purpose" retrieved value is "Storing test data"

Now I need to write some text using protractor to that json file from which we read the values. e.g. The original json file should have extra data written from protractor code.

{ "Name":"Json Test Data", "Purpose":"Storing test data", "user1":"[email protected]" }

2

There are 2 best solutions below

2
On

This will work.

var fs = require('fs');
var text = "Text To be Written"
var outputFilename = 'Output.json';
fs.writeFile(outputFilename, text, function(err) {
    if(err) {
        console.log(err);
    }
    else {
        console.log("JSON saved to " + outputFilename);
    }
});
0
On

TypeScript:

import * as fs from 'fs';

writeFile(filename: string, fileContents: string): void {
    fs.writeFile(filename, fileContents, (err) => {
        if (err) {
            console.error(err);
        } else {
            console.log(`File saved to ${ filename }`);
        }
    });
}