Reading text from the web and writing to a JSON file This code reads text from the web using a WebDriver element and writes data to a JSON file. I had to use if-else (to write only the last line to the JSON file) just because of the asynchronous behaviour of NodeJs, otherwise I was trying to add fs.appendFile(filepath,"}") in the end to close the JSON file.

I just want you to optimize this snippet as I am new to NodeJs.

saveListOfAllCitiesIntoJsonFile () {
    var filePath = './Data/AllCitiesAvailableOnWeb.json';
    var CITY_COUNT = pageElements["CityCount"];
    var AllCity = homePageElements['AllCity'];
    var CityList = homePageElements['CityList'];
    super.findElementByClassName(AllCity).click();
    super.findElementsByClassName(CityList).then(function (element_CityName) {
        fs.truncate(filePath, 0);
        fs.appendFile(filePath, "{" + "\n");
        var jsonData = null;
        var elementData = null;
        for (var i = 0; i &lt; CITY_COUNT; i++) {
            elementData = element_CityName[i].getText();
            if (i === CITY_COUNT - 1) {
                elementData.then(function (text) {
                    jsonData = "\"" + text + "\"" + ": " + "\"/hotels-in-" + text;
                    fs.appendFile(filePath, jsonData + "\"" + "\n" + "}", function (err) {
                        if (err) {
                            console.log(err);
                        }
                    });
                });
            }
            else {
                elementData.then(function (text) {
                    jsonData = "\"" + text + "\"" + ": " + "\"/hotels-in-" + text;
                    fs.appendFile(filePath, jsonData + "\"," + "\n", function (err) {
                        if (err) {
                            console.log(err);
                        }
                    });
                });
            }
        }
    });
}
saveListOfAllCitiesIntoJsonFile () {
    var filePath = './Data/AllCitiesAvailableOnWeb.json';


Now if I was a consumer of this API, the function name is very vague in a sense that I don't know where that file is or what the file is for. What is this JSON file you speak of? Why is it saving cities?

If you start to reason "read the source code", then that's the wrong way to write code. Better if you either make the function more flexible by letting the caller provide a path or make the name more meaningful in what it does. That way, the caller knows where the file is going to or what that file is for.

var CITY_COUNT = pageElements["CityCount"];
var AllCity = homePageElements['AllCity'];
var CityList = homePageElements['CityList'];


I'm saving cities, but what are pageElements and homePageElements? Where do they come from? How are they related to the function that's saving to the JSON? It's best if you break apart functions into small units of functionality. Functions that do too much are hard to test or even eyeball for flaws. 

Aside from the comment given, where it advises to NOT construct JSON this way, you are also hitting the filesystem for every chunk of syntax. That's inefficient. Constructing JSON using the stringify function will allow you to create a string once. You can then write that string to the filesystem once. No chunks. No multiple writes.

I suggest you break this operation into two: One function that reads the data into a data structure, and another function that accepts the data structure, serializes it and writes to the file.

function getCitiesFromPage(pageElements, homePageElements){
  // traverse and collect cities from pageElements and homePageElements
  return cities;
}

function writeCitiesToFile(data, path){
  // serialize data and write to path
}

function saveCitiesToFile(){
  let cities = getCitiesFromPage(pageElements, homePageElements);
  writeCitiesToFile(cities, './Data/AllCitiesAvailableOnWeb.json');
}