nodejs read and write file

nodejs

To read and write files in Node.js, you can use the fs module. This module provides a set of functions to read, write, and manipulate files in a Node.js application.

Here are some examples of how you can use the fs module to read and write files:

Reading a file:

const fs = require('fs');

fs.readFile('/path/to/file', (error, data) => {
  if (error) {
    console.error(error);
    return;
  }

  console.log(data);
});

The readFile() function reads the contents of a file and returns it as a buffer. You can also pass an encoding as the second argument, in which case the file contents will be returned as a string.

Writing a file:

const fs = require('fs');

const content = 'Hello World';

fs.writeFile('/path/to/file', content, (error) => {
  if (error) {
    console.error(error);
    return;
  }

  console.log('File written successfully');
});

The writeFile() function writes the specified content to a file. If the file does not exist, it will be created. If the file already exists, it will be overwritten.