Node.js file system

The Node.js fs module provides an API for working with the file system in Node.js. With this module, you can read and write files, create directories, get information about files and directories, and more.

Here are some examples of how to use the fs module:

Reading a File

r‮i:ot refe‬giftidea.com
const fs = require('fs');

fs.readFile('file.txt', 'utf8', (err, data) => {
  if (err) throw err;
  console.log(data);
});

This code reads the contents of a file named file.txt and logs it to the console. The readFile() method takes three arguments: the name of the file to read, the encoding to use (in this case, utf8), and a callback function that will be called when the file is read. The callback function takes two arguments: an error object (if an error occurs), and the data read from the file.

Writing to a File

const fs = require('fs');

fs.writeFile('file.txt', 'Hello, world!', (err) => {
  if (err) throw err;
  console.log('File written successfully!');
});

This code writes the string "Hello, world!" to a file named file.txt. The writeFile() method takes three arguments: the name of the file to write, the data to write, and a callback function that will be called when the file is written.

Creating a Directory

const fs = require('fs');

fs.mkdir('mydir', (err) => {
  if (err) throw err;
  console.log('Directory created successfully!');
});

This code creates a directory named mydir. The mkdir() method takes two arguments: the name of the directory to create, and a callback function that will be called when the directory is created.

These are just a few examples of how to use the fs module in Node.js. For more information, check out the official Node.js documentation on the fs module.