Is it possible to create a json file


#1

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 ?


#2

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


#3

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


#4

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 ?


#5

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


#6

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 ?


#7

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.


#8

OK i’ll check the methods guide thank you