nodejs write json to file in javascript

To write JSON to a file using Node.js in JavaScript, you can use the fs (File System) module which provides an API for interacting with the file system in a manner closely modeled around the POSIX family of standards.

You can use the fs.writeFile() method to write data to a file asynchronously. Here's an example code snippet that demonstrates how to write JSON data to a file using Node.js:

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

const data = {
  id: 1,
  name: 'John Doe',
  email: 'johndoe@example.com'
};

const filePath = 'data.json';

fs.writeFile(filePath, JSON.stringify(data, null, 2), (err) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(`Data written to ${filePath} successfully`);
});
318 chars
18 lines

In the above code, we first require the fs module to access its functions. Then, we define the JSON object that we want to write to a file. We also specify the file path where we want to write the JSON data.

We then call the fs.writeFile() method and pass the file path, the JSON data to write, and an error-first callback function as arguments. In the callback function, we check for any errors, and if there are no errors, we log a success message to the console.

Note that we use JSON.stringify() to convert the JavaScript object to a JSON string before writing it to the file. The null and 2 parameters passed to JSON.stringify() are optional and specify the replacer and space arguments respectively. In this case, we're using null as the replacer and 2 as the space argument to add indentation to the output.

gistlibby LogSnag