In Node.js, you can write to files using the fs (File System) module.

-> Below I am sharing some examples which can helping you to do write operation with file

Writing Synchronously:

  • In this example, writeFileSync is a synchronous method that writes content to the specified file.
  • It can block the execution of your program until the write operation is complete.

Example:

const fs = require('fs');

const filePath = 'example.txt';
const content = 'Hello, this is some content!';

try {
  fs.writeFileSync(filePath, content);
  console.log('File written successfully.');
} catch (error) {
  console.error('Error writing to file:', error);
}

Writing Asynchronously:

  • In this example, writeFile is an asynchronous method that takes a callback function.

Example:

const fs = require('fs');

const filePath = 'example.txt';
const content = 'Hello, this is some content!';

fs.writeFile(filePath, content, (error) => {
  if (error) {
    console.error('Error writing to file:', error);
  } else {
    console.log('File written successfully.');
  }
});

Appending to a File:

  • If you want to append content to an existing file, you can use fs.appendFile

Example:

const fs = require('fs');

const filePath = 'example.txt';
const contentToAppend = '\nThis content is appended.';

fs.appendFile(filePath, contentToAppend, (error) => {
  if (error) {
    console.error('Error appending to file:', error);
  } else {
    console.log('Content appended successfully.');
  }
});

Support On Demand!

                                         
Node