write json to a file in javascript

To write JSON to a file in JavaScript, you can use the built-in fs module in Node.js. Here's an example code snippet that demonstrates how to write a JSON object to a file:

index.tsx
const fs = require('fs');

const data = {
  name: 'John Smith',
  age: 42,
  email: 'john.smith@example.com'
};

const jsonData = JSON.stringify(data);

fs.writeFile('data.json', jsonData, err => {
  if (err) {
    console.error(err);
    return;
  }
  console.log('Data written to file');
});
294 chars
18 lines

In the above code, we first import the fs module, create a JavaScript object called data, and then convert it to a JSON string using JSON.stringify. We then use the writeFile function to write the JSON string to a file called data.json. The writeFile function takes three arguments: the file name, the data to write, and a callback function to execute once the operation is complete. If an error occurs during the write operation, we print the error to the console. Otherwise, we print a success message.

related categories

gistlibby LogSnag