What could be the reason that the elements are not being written to a file in this for loop?

Check out my code below:

var data = require('./campSample.json');
var dataArray = data.resultset.result;
var fs = require('fs');


for(var i = 0; i < dataArray.length; i++){
    fs.writeFile("./campList", dataArray[i]["-facilityName"], function (err) {
        if(err){
            return console.log(err);
        }
    });
}

I am attempting to iterate through each item in the array using a for loop, extract the facilityName property, and write it to a file. However, when I execute the code above, only the facilityName of the first item in the array is being written. Is there a more efficient approach to achieve this task? The campSample.json provided here is just a sample, with the actual array containing around 4000 items. Here is a snippet of the contents of campSample.json:

{
  "resultset": {
    "-count": "4904",
    "-resultType": "campgrounds",
    "result": [
      {
        "-availabilityStatus": "N",
        "-contractID": "GA",
        "-contractType": "STATE",
        "-facilityID": "530145",
        "-facilityName": "A. H. STEPHENS STATE HISTORIC PARK",
        "-faciltyPhoto": "/webphotos/GA/pid530145/0/80x53.jpg",
        "-latitude": "33.5633333",
        "-longitude": "-82.8966667",
        "-shortName": "C145",
        "-sitesWithAmps": "Y",
        "-sitesWithPetsAllowed": "Y",
        "-sitesWithSewerHookup": "N",
        "-sitesWithWaterHookup": "Y",
        "-state": "GA"
      },
      {
        "-availabilityStatus": "N",
        "-contractID": "OH",
        "-contractType": "STATE",
        "-facilityID": "960023",
        "-facilityName": "A.W. MARION STATE PARK",
        "-faciltyPhoto": "/webphotos/OH/pid960023/0/80x53.jpg",
        "-latitude": "39.6336111",
        "-longitude": "-82.8747222",
        "-shortName": "P023",
        "-sitesWithAmps": "Y",
        "-sitesWithPetsAllowed": "Y",
        "-sitesWithSewerHookup": "N",
        "-sitesWithWaterHookup": "N",
        "-state": "OH"
      },
      {
        "-availabilityStatus": "N",
        "-contractID": "NRSO",
        "-contractType": "FEDERAL",
        "-facilityID": "72346",
        "-facilityName": "ACKER ROCK LOOKOUT",
        "-faciltyPhoto": "/webphotos/NRSO/pid72346/0/80x53.jpg",
        "-latitude": "43.0523056",
        "-longitude": "-122.6456111",
        "-shortName": "ARCL",
        "-sitesWithAmps": "N",
        "-sitesWithPetsAllowed": "Y",
        "-sitesWithSewerHookup": "N",
        "-sitesWithWaterHookup": "N",
        "-state": "OR"
      }
    ]
  }
}

Answer №1

To optimize performance, make sure to gather all the names in advance and then insert them into the ./campList file with a single input/output operation.

var names = dataRecords.map(function(item) {
  return item["-facilityName"];
}).join('\n');
fs.writeFile("./campList", names, function(error) {
  if (error) {
    return console.log(error);
  }
});

Answer №2

According to the documentation for writeFile:

It is not safe to use fs.writeFile multiple times on the same file without waiting for the callback. In such cases, it is advised to use fs.createWriteStream instead.

Moreover:

Asyncronously writes data to a file, replacing the existing file if there is one.

Answer №3

Based on the feedback you provided, it seems like you want to add content to a file. The code below demonstrates how you can achieve this:

const data = require('./campSample.json');
const dataArray = data.resultset.result;
const fs = require('fs');

for(let i = 0; i < dataArray.length; i++){
    fs.appendFile("./campList", dataArray[i]["-facilityName"]+'\r\n', function (err) {
        if(err){
            return console.log(err);
        }
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am having issues with the accuracy of my JavaScript number validation function

function CheckIfNumeric() { var quantity = jQuery("#txtShippedQuantity").val(); quantity = quantity.toString(); for (i = 0; i < quantity.length; i++) { var character = quantity.charAt(i); if (isNaN(character)) { ...

Learn how to retrieve a meta tag's content value and perform a subtraction operation

I need assistance in retrieving the value of the meta tag content and performing a subtraction operation on it. Could someone lend me a hand with this, please? The meta tag is structured as follows: <meta itemprop="price" content="1699"> I ha ...

Utilize JSON API data in Laravel or integrate it into an iOS application

I am utilizing Laravel fractal for transforming my API data. Within my database, there exists a timestamp such as "2015-02-15 14:34". However, I wish to transform this into "Time remaining" instead of just displaying the timestamp. For example, "2015-03- ...

Developing a Java Spring Boot API endpoint to retrieve a JSON representation of a collection of objects

I am currently working on developing an endpoint that will provide a JSON response containing a list of objects. The structure of the objects is as follows: units: [ { id: #, order: #, name: "" concepts: [ ...

Instafeed.js experiencing issues with photo uploads

Can instafeed.js function without an active website? I am attempting to incorporate my friend's Instagram photos into the website I'm designing for him, but the site is not yet 'live/active' so I suspect that may be the reason it's ...

Utilizing ng-style with a ForEach loop on an Object

How can I dynamically add a new style property to objects in an array in Angular, and then use that property inside ng-style? CommentService.GetComments(12535372).then(function () { $scope.comments = CommentService.data(); angular.forEac ...

What is the best way to choose a specific word in a single row from a column that contains an array?

I need to filter a column that stores arrays of strings based on a specific keyword. However, when I attempt to do this, I encounter the following error: function contains(character varying[], unknown) does not exist Below is the query I am using: SELECT ...

Encountering an unknown provider error in AngularJS while using angular-animate

Upon removing bower_components and performing a cache clean, I proceeded to reinstall dependencies using bower install. However, the application failed to load with the following error message: Uncaught Error: [$injector:unpr] Unknown provider: $$forceRefl ...

Unable to convert JSON into a recognizable Object format

During my program testing, I encountered an issue where I needed to convert APIGatewayProxyResponse into an object to access its values. Here is a snippet of the APIGatewayProxyResponse.Body (which is in string format): "[{"date": "2020-03-06", "value": ...

Can you please explain the purpose of this code block and whether it is necessary for me to use in my project

I possess highly sensitive information that needs to be handled with care. Can you explain the purpose of this code snippet and its significance? app.use(function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.hea ...

Retrieve data from the android database table

I am struggling to retrieve the array of rows where the username matches the one in the database table. However, the JSON result only provides me with the last row that matches. Example Table: james 14 <a href="/cdn-cgi/l/email-protection" class="__cf ...

How can I forward a post request to a different URL in a node.js application?

I am attempting to forward a POST request from one server to another server while including additional parameters from the initial request. Take a look at the code snippet below. app.use(bodyParser.urlencoded({ extended: true })); app.post('/pay1&ap ...

The React application deployed on GitHub Pages is displaying a blank white screen

I developed a simple meme generator app in React.js as an exercise to learn web development, but I am facing issues while trying to host it on Github pages. I followed all the necessary steps such as installing gh-pages with node, updating packages.json wi ...

I must update a bootstrap class name within multiple layers of divs by referring to the parent class

My code structure is set up like this: <div id="main-parent"> <div class="child2"> <div> child2 </div> </div> <div>child3</div> - - - - <div class="ch ...

Creating a factory class in Typescript that incorporates advanced logic

I have come across an issue with my TypeScript class that inherits another one. I am trying to create a factory class that can generate objects of either type based on simple logic, but it seems to be malfunctioning. Here is the basic Customer class: cla ...

Struggling to fix the "TypeError: not a function" issue

Hey everyone, I've been working on setting up an Express app to connect to mongodb using the node driver for mongodb. Unfortunately, I keep encountering a TypeError: mongodbconnect is not a function. I double-checked my export/import process and made ...

Could the lack of component rerendering when updating state during delete in Angular services be causing issues?

I have two components that are interacting with each other: todos.services.ts: import { Injectable } from '@angular/core'; import { TodoItem } from '../interfaces/todo-item'; @Injectable({ providedIn: 'root', }) export cla ...

Issue with uploading images in Summernote

It seems that my onImageUpload function in the summer note jQuery plugin is not functioning as expected. I am trying to upload an image to a folder location different from the default summernote directory. How can this be handled? index.php <textarea ...

`The challenge of properly handling quotation marks within quotation marks in JavaScript string literals

I am having trouble displaying text in a JavaScript tooltip Despite my efforts to escape the quotes and eliminate any line breaks, I keep encountering unterminated string literals. The specific text I want to show is: "No, we can't. This is going t ...

Exploring how to browse and dynamically assign image sources with JavaScript/jQuery in an Asp.net mvc 4 framework

On my .cshtml page, I have an <img/> tag. <img id="ImageID" alt="" width="100%" height="100%" /> I want to dynamically set the src attribute by selecting the image file path using a file control. Although I attempted the following code in my ...