Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

File System Operations in Node.js

File System Operations in Node.js

Node.js provides a built-in module called fs (File System) that allows you to perform various file-related operations, such as reading from and writing to files, creating directories, and more. Here's an overview of common file system operations in Node.js:

1. Importing the fs Module:

To use the fs module, you first need to require it in your JavaScript file:

const fs = require('fs');
 

2. Reading Files:

The fs.readFile() function is used to asynchronously read the entire contents of a file.

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

3. Writing Files:

The fs.writeFile() function is used to asynchronously write data to a file. If the file already exists, it will be overwritten.

fs.writeFile('file.txt', 'Hello, World!', 'utf8', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('File written successfully.');
  }
});
 

4. Creating Directories:

The fs.mkdir() function is used to asynchronously create a directory.

fs.mkdir('newDirectory', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Directory created successfully.');
  }
});
 

5. Checking if a File or Directory Exists:

You can use fs.existsSync() to synchronously check if a file or directory exists.

if (fs.existsSync('file.txt')) {
  console.log('File exists.');
} else {
  console.log('File does not exist.');
}
 

6. Reading Directories:

The fs.readdir() function is used to asynchronously read the contents of a directory.

fs.readdir('myDirectory', (err, files) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Files in directory:', files);
  }
});
 

7. Renaming Files or Directories:

The fs.rename() function is used to asynchronously rename a file or directory.

fs.rename('oldName.txt', 'newName.txt', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('File renamed successfully.');
  }
});
 

8. Deleting Files or Directories:

The fs.unlink() function is used to asynchronously remove a file, and fs.rmdir() is used to remove an empty directory.

fs.unlink('fileToDelete.txt', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('File deleted successfully.');
  }
});

fs.rmdir('directoryToDelete', (err) => {
  if (err) {
    console.error(err);
  } else {
    console.log('Directory deleted successfully.');
  }
});

 

9. Checking File Information:

The fs.stat() function is used to asynchronously retrieve information about a file.

fs.stat('file.txt', (err, stats) => {
  if (err) {
    console.error(err);
  } else {
    console.log('File size:', stats.size, 'bytes');
    console.log('Last modified:', stats.mtime);
  }
});