0
let data= {
        timestamp:time,
        OSName:osname,
        IP:userdata.IPv4,
        country:userdata.country_name,
        browser:broname
    }

I want to store these values into a JSON file or js file, so that I can fetch them later on. Please help me with this, how can I store them? Also, these value update every time when page reload; then a new object should be made.

Jeremy Thille
  • 25,196
  • 9
  • 41
  • 59
  • Did you at least look it up? Did you google "[node.js how to write data to a file](https://www.google.com/search?q=node.js+how+to+write+data+to+a+file&oq=node.js+how+to+write+data+to+a+file)" before asking for help? – Jeremy Thille Oct 01 '21 at 07:16
  • Use the `fs` module to write to file, and use `JSON.stringify(your_object)` to convert it to string. – darklightcode Oct 01 '21 at 07:17
  • I took the liberty to format your question (punctuation, commas, capital letters etc.) to make it more readable. – Jeremy Thille Oct 01 '21 at 07:18

1 Answers1

0

NodeJS has his own lib for this, fs (Docs).

You need to import it (I used Vanilla JS, for more general solution)
const fs = require('fs');

And then you can use writeFileSync to save it (Docs)
In your case, you would need to do something like this:
fs.writeFileSync(<filename>, JSON.stringify(<yourObject>));

  • yeah it's working in mine also. –  Oct 01 '21 at 08:41
  • yes it is working but when i refresh my page then a new value is appended to the json file but there is no punctuation of , for seperation of json objects like it stores like {...}{...}{...} without separation of coma this is the main project hope you get it. Or am making a url shortener web app where someone open the url shorter links then i have to store these values and then displayed on the details. actually am learning all these buidling my first project please help – ashish saini Oct 01 '21 at 16:18
  • You can overwrite the content of the file if that works for you (Here you have a [related question](https://stackoverflow.com/questions/43892482/whats-the-best-way-to-overwrite-a-file-using-fs-in-node-js)). If you need to add data to the current file, you can first read the content of the file with [fs.readFile](https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback), parse it to JSON and append the new object to it, before writing the changes. – Faus Rodriguez Oct 03 '21 at 10:31