fs.writefile

const fs = require('fs');

const content = 'This is the content to be written to the file.';
const filePath = 'example.txt';

fs.writeFile(filePath, content, (err) => {
  if (err) {
    console.error('Error writing to file:', err);
    return;
  }
  console.log('Content has been written to the file successfully.');
});

Explanation:

  1. Import the File System module: Import the built-in File System module in Node.js using require('fs'). This module allows interaction with the file system in a non-blocking way.

  2. Define content: Create a variable content containing the string data that you want to write to the file.

  3. Define file path: Set the filePath variable to specify the location and name of the file where the content will be written.

  4. Write file: Use the fs.writeFile() method to write the content to the specified filePath. The method takes three parameters: the file path, the content to be written, and a callback function that handles potential errors.

  5. Callback function: The callback function is triggered once the write operation is completed. It checks for errors during the writing process. If an error occurs, it logs an error message to the console. If the write operation is successful, it logs a success message indicating that the content has been written to the file.