Is it possible to create a json file

Hi
I’m a student and I’m trying to do a function with JS and nodejs to create a .json file.

here is my code

json(event){
const fs = require(‘fs’);> json = {
one: 1,
two: 2
}
json = JSON.stringify(json);
fs.writeFile(’./foo.json’, json, (err) => {
if (!err) {
console.log(‘done’);
}
});
}

But i get an error and the console says me

Uncaught TypeError: fs.writeFile is not a function

the problem is that i’ve test this code in a simple js file and it worked well so i don’t understand, can someone help me ?

Are you trying to do this on the client? There are no fs functions there.

use https://jsonformatter.org/json-editor for creating , validating JSON file.

I do the function on the same page than my web app so i guess it is on my client. So where i should do my code to get the fs function ?

Anything inside the /server folder, and anything imported by a file there, runs on the server.

Sorry but i don’t really understand i should create this function on the server dirrectory and than import this function on my react app ?

No, if you imported it to the client, then it would run on the client. You’ll have to create a method so that the client can message the server to run your function.

1 Like

OK i’ll check the methods guide thank you