0

I have object in my JavaScript file and empty json file. How can I just write this object to the json file? I tried "require" or "import" but get errors all the time. What is generally correct way to write info to json file?

function readInput() {
  fetch("./input.json")
    .then((response) => response.json())
    .then((data) => {
       // do some work with data
    });
}

now I want to write data to new json file. When I do this as in tutorials

const fs = require('fs')

I get "require is not defined" and it suggests me to conver require to

import { writeFile } from 'fs';


now I have error "Cannot use import statement outside a module"

Cannot understand what is needed to write to json file

1 Answers1

1

JavaScript has no built-in features for writing to files. It depends on the host environment to provide that sort of thing.

The instructions you found appear to be for Node.js which provides the fs module and supports CommonJS and ES6 modules.

However, you appear to be trying to run your code in a web browser via a <script> element. Web browsers do not provide JavaScript with any APIs for writing files.

You could generate a download and the resulting file will either prompt the user with a SaveAs dialog or just save it to their downloads folder depending on how their browser is configured.

You could also use fetch to make an HTTP POST or PUT request and then use server side code to save the data (keeping in mind that you don't want to create an unauthenticated public API for writing data to your server as that just invites vandalism and worse.

You could also consider localStorage if you want to persist the data in the browser rather than sharing it between users or exporting an actual file.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335