Writing to files in Node.js with example

To write to a file in Node.js, you can use the built-in fs (file system) module. The fs module provides a variety of methods for working with the file system, including reading and writing files.

Here’s an example of how you can write to a file in Node.js:

const fs = require('fs');

const data = 'Hello, this is a sample data.';

fs.writeFile('sample.txt', data, (err) => {
  if (err) throw err;
  console.log('Data written to file');

In this example, we first require the fs module, then we create a string variable data that contains the data we want to write to a file.

Next, we call the fs.writeFile method, which takes the following arguments:

  1. The file path and name, in this case 'sample.txt'.
  2. The data to be written to the file, in this case data.
  3. A callback function that is called once the write operation is complete. This function takes an error argument, which will be null if the write operation was successful, and an error otherwise.

In the callback function, we check if an error occurred during the write operation, and if so, we throw the error. Otherwise, we log a message indicating that the data has been written to the file.

This code will create a new file named sample.txt in the same directory as your script and write the string 'Hello, this is a sample data.' to the file. If the file already exists, its contents will be overwritten.