Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript How to save a javascript calculated value in a file and read from the file

hiii

Coder
Hi,
I fetched a data array from a web platform and calculated their average. Now I want to store this value inside a file every time to track the trend of the data.
 
JavaScript does not have file capabilities. If it's a small amount of data you could store it in a cookie. Otherwise you'll need to store in on the server.
 
Do you know how long it takes to learn node.js from scratch? and is its structure very different than the JS?
I don't know what it would mean to "learn node.js from scratch". Depends on your experience, and how much you want to learn. If you know JS it should not be a big deal. Language-wise they are pretty much the same, but differ in some capabilities. See for example https://www.javatpoint.com/javascript-vs-nodejs

I thought from your original post that you have already created some kind of script ? Why don't you share that, or at least tell us what exactly you have created so far ?
 
JavaScript:
function hostCPU() {
   sum1=0;
   count1=0;
  fetch("url....")
        .then((response) => response.json())
        .then((data) => monitorHostCPU(data))
        .catch(() => renderError());
 }
function monitorHostCPU(data) {
  // Get text elements
  const displayName = document.getElementById("displayName");
  const dataPoints = document.getElementById("dataPoints");
  const error = document.getElementById("error");


   result=Object.values(data.dataResult.dataPoints);
   resultStr=String(result);
   resultArr=resultStr.split(',');
   for(i=0; i<resultArr.length;i++){
      if (resultArr[i]!=="")
        if (i%2==1){
          sum1+=Number(resultArr[i]);
          count1+=1;
        }
        else{
          //str+="|" ;
          sum1+= 0;
        }
    
    }
  average1=sum1/count1;
  list.push({metricName:data.displayName, metricValue:average1});
  error.innerHTML ="";
  res.innerHTML = average1;
  disName.innerHTML = "Host CPU Usage";
  if (average1>500 ){
    res.style= "color:#f00;";
  }
}

I want to save the average inside a database or a file every time the page gets refreshed. I also can save the values in local storage but I couldn't save an array containing the averages. I just can save one value and update it.
 
Thanks, interesting. I did not know about the fetch API.

Can you explain your last sentence in more detail ? If I understand it correctly you can save individual values but have trouble saving an array ? How exactly are you doing both ? And what happens when you try to save the array ? Do you get an error in the console ?
 
Let me bud in here for a sec and throw my 2 cents in.
"How long does it take to learn nodejs?" Depends on you, Right? - BUT nodejs is JavaScript and you should know that already. It does have some extra stuff - like reading and writing files and I just gave you those commands. Some servers already have nodejs installed. If it does bob's your uncle. If not install it - try it - stop wasting time time here asking questions that may clear up once you try nodejs.
Go For It!!!
 
Thanks, interesting. I did not know about the fetch API.

Can you explain your last sentence in more detail ? If I understand it correctly you can save individual values but have trouble saving an array ? How exactly are you doing both ? And what happens when you try to save the array ? Do you get an error in the console ?
Yes, I can save one value every time I refresh the page. using the if statement I told if localStorage is empty setItem but if it's not empty push the new average into the array. it doesn't return any error but it doesn't push the new value either. So I just changed my mind and I might use node.js or write the entire code in python or php
 
Personally I would try to solve that problem rather than switching to another language. I'm not sure how exactly you "push the new average into the array", and why that does not seem to work. If this does not work in JS I rather doubt that it will work in Node.js. I guess you are talking about this statement

list.push({metricName:data.displayName, metricValue:average1});

Have you examined the value of list before and after the push and have you checked the console log in the debugger ? I seem to be asking this last question in every post 🙄🙂 Also not sure what you mean with localStorage being empty and setItem. I don't see any of that in the code you posted. Details, details....

But ok, it's you call if you want to try some other language or JS variant.
 
Personally I would try to solve that problem rather than switching to another language. I'm not sure how exactly you "push the new average into the array", and why that does not seem to work. If this does not work in JS I rather doubt that it will work in Node.js. I guess you are talking about this statement

list.push({metricName:data.displayName, metricValue:average1});

Have you examined the value of list before and after the push and have you checked the console log in the debugger ? I seem to be asking this last question in every post 🙄🙂 Also not sure what you mean with localStorage being empty and setItem. I don't see any of that in the code you posted. Details, details....

But ok, it's you call if you want to try some other language or JS variant.
Code:
exist=JSON.parse(localStorage.getItem('cpu')) || [];
    if(exist) {
        exist.push(average);
        localStorage.setItem(cpu', exist);}
    else
        localStorage.setItem('cpu', average1);
 
Interesting, thanks. I did not know about localStorage 😳
Did you notice the missing quote in the first setItem command ? And I ask once more, have you checked the console log ? Because there should have been an error.
But I am not sure it would work even with the quote. setItem() expects a string as value, and you are passing it a list of more than one items. When that has been stringified, the result may not be what you expect.
 
Interesting, thanks. I did not know about localStorage 😳
Did you notice the missing quote in the first setItem command ? And I ask once more, have you checked the console log ? Because there should have been an error.
But I am not sure it would work even with the quote. setItem() expects a string as value, and you are passing it a list of more than one items. When that has been stringified, the result may not be what you expect.
No problem.
Yes, I wanted to correct it but I couldn't. Yes, every time I do check the errors and nothing. You know the problem is that in the localstorage the items are in string and when I convert it into a number it's no longer an array. I'm kinda stuck there that's why I think it would be faster if I start it in a new language. In the beginning, we didn't want to store the values but in the middle of writing the program, we decided to keep track of them.
 

Latest posts

Buy us a coffee!

Back
Top Bottom