retrieve data from JSON file

function retrieveDataFromProfiles(){
  const fs = require('fs')
  fs.readFile('src/data/profileInfo.json', function(error, data){
    if(error){
    alert(error);
   }
  var profileData = JSON.parse(data);
  //retrieves the JSON data of profiles
  return profileData;
 });
}

I am attempting to extract the JSON data from this function and assign it to a variable in another function. However, I am uncertain about the correct method to achieve this, as the traditional return approach is not effective. I have been advised to utilize either a promise or async function, but I lack clarity on how to proceed with that.

Answer №1

Make sure to return a Promise from the function, and resolve it after reading the JSON data.

function retrieveUserProfiles() {
  const fs = require("fs");
  return new Promise((resolve, reject) => {
    fs.readFile("src/data/profileInfo.json", function (err, data_array) {
      if (err) {
        // Reject if an error occurs
        reject(err);
      }
      var json = JSON.parse(data_array);
      // Resolve when data is retrieved
      resolve(json);
    });
  });
}

When calling the function, remember to use either async/await or then/catch.

retrieveUserProfiles()
  .then(json => console.log(json))
  .catch(err => alert(err)); // Display alert for errors

Answer №2

let user_profile = fs.readFileSync(__dirname + '/data/profileInfo.json',(err,data)=>{});

Parsed_user_profile = JSON.parse(user_profile)

This solution worked for me, although the previous comment also had a valid suggestion.

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

Outdated Information Found in Meteor Collection

Previously, I had code that successfully made a HTTP get call from the server, utilized EJSON.parse to parse data retrieved from a JSON-formatted URL, and then added information from the parsed data to a Meteor collection. However, after updating to Meteor ...

Is the Await keyword failing to properly pause execution until the promise has been fulfilled?

I'm currently working on manipulating a variable within an async function, and I've noticed that the variable is being returned before the completion of the data.map function below. Even though I have the await keyword in place to pause the code ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

Promise not being properly returned by io.emit

io.emit('runPython', FutureValue().then(function(value) { console.log(value); //returns 15692 return value; // socket sends: 42["runPython",{}] })); Despite seeing the value 15692 in the console, I am encountering an issue where the promise ...

OutOfBoundsException due to an invalid index value for the string length

I've recently started working with Android and I'm trying to send the value of an editText using JSON to a server. However, I keep encountering an error "StringIndexOutOfBoundsException" and I'm unsure of how to resolve it. Here is my code: ...

Incorrectly loading static images in React SSR

I am currently working on a React SSR app and my folder structure looks like this: My static express middleware successfully handles static files and images in the tag on the client side: However, when I attempt to renderToPipeableStream for server-side ...

Navigating the storing and organizing of user data through Firebase's simplistic login feature for Facebook

As I work on my AngularJS and Firebase-powered website project, I aim to leverage Facebook login for seamless user connectivity. While Firebase's simple login feature promises an easier authentication process, I face the challenge of effectively acces ...

What is the process for toggling a button using Vue.js?

Important Note: Implemented Vue.js and Vuetify.js for both functionality and styling. Utilizing the :class and @click properties, I managed to alter the background color of a button to a specified color. However, this modification is being applied to all ...

Steps to retrieve the array values for a specified descendant in a JSON data structure

{ "hasLoadMore": true, "groups": [ { "order": 0, "title": "string", "total": 0, "dateFormat": "string", "messages": [ { "commsId": 0, "commsDirectionCode": "string", "commsReasonCR ...

Passing methods from child to parent components in Vue2 looped componentsHere is a

Currently, I am iterating through the root component, which contains a child component within it. <root-select v-for="offer in offers" > <child-options v-for="item in options" > </child-options> </root-select> However, when ...

Implement a one-second delay before nesting another animation

I'm currently utilizing a timeout function, but I am interested in using a delay instead. My goal is to have the second animation start when one second has passed from the beginning of the first animation, and it should be a linear animation. How can ...

Instructions on creating a number increment animation resembling Twitter's post engagement counter

I've been attempting to replicate the animation seen on Twitter's post like counter (the flipping numbers effect that happens when you like a post). Despite my best efforts, I can't seem to make it work. Here is what I have tried: $(fun ...

What could be causing the SwifyJSON dictionaryValue to be blank?

Trying to parse JSON data in my iOS app using SwifyJSON and socket.io, but encountering an issue where the .dictionaryValue of the response is coming back as nil. This is how the data is being sent from the server: socket.emit('hasBeenMatched', ...

Identifying when a browser is closed with multiple tabs open in Internet Explorer

I need to detect when a browser tab is closed in order to trigger a Struts action. I have successfully implemented this for a single tab using the following JavaScript code: <script type="text/javascript> function loadOut() { if ((window.event.c ...

Positioning an HTML table with the use of a for loop in JavaScript

Detail of the project: -Utilizing a javascript for loop, my program extracts data from an external javascript array titled "arrays.js" and organizes it into an HTML table. The goal is to align the appropriate data under the "Date Name Address Amount" colum ...

Gather all characters following a particular string and combine them into one unified string

I have a unique string that contains specific information: { "getInfoOne": { "sp_name": "analytics.info_one_data", "sp_input_params": { "req_url_query_params": [], "req_body_par ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

Error: Unable to locate module adaptivecards-templating

After adding the module through the command: npm install adaptive-expressions adaptivecards-templating --save and importing it, I encountered an error when trying to run my application: ...

Switch out the arrow icon in the dropdown menu with an SVG graphic

Looking for a way to customize the dropdown caret in a semantic-ui-react component? Here's how it currently appears: <Dropdown className="hello-dropdown" placeholder="Comapany" onChange={this.someFunction} options={som ...

Guide on how to retrieve the parent element's number when dragging starts

Within my div-containers, I have a collection of div-elements. I am looking to identify the parent number of the div-element that is currently being dragged For example, if Skyler White is being dragged, the expected output should be "0" as it is from the ...