Comprehensive Guide to `fs-extra` NodeJS File System Operations

Comprehensive Guide to `fs-extra` NodeJS File System Operations

The `fs-extra` is a module for NodeJS that provides extended filesystem capabilities
that go beyond the standard `fs` library. This library adds dozens of useful methods
that streamline file operations, making it easy to copy, move, delete, and manipulate
files and directories with node.

Getting Started with `fs-extra`

  
    const fs = require('fs-extra');
    
    // Ensuring a directory exists
    fs.ensureDir('./directory')
      .then(() => console.log('Directory created'))
      .catch(err => console.error(err));
  

Useful API Methods

Copying Files and Directories

  
    const src = './src';
    const dest = './dest';

    fs.copy(src, dest)
      .then(() => console.log('Files copied'))
      .catch(err => console.error('Error copying files:', err));
  

Removing Files and Directories

  
    const path = './path-to-delete';

    fs.remove(path)
      .then(() => console.log('Path deleted'))
      .catch(err => console.error('Error removing path:', err));
  

Reading JSON Files

  
    const file = './file.json';

    fs.readJson(file)
      .then(data => console.log('JSON data:', data))
      .catch(err => console.error('Error reading JSON file:', err));
  

Writing JSON Files

  
    const file = './file.json';
    const obj = { name: 'fs-extra' };

    fs.writeJson(file, obj)
      .then(() => console.log('JSON successfully written'))
      .catch(err => console.error('Error writing JSON file:', err));
  

Checking if a Path Exists

  
    const path = './some-path';

    fs.pathExists(path)
      .then(exists => console.log('Path exists:', exists))
      .catch(err => console.error('Error checking path existence:', err));
  

Application Example

Here is a small application that demonstrates a backup utility using `fs-extra` APIs:

  
    const fs = require('fs-extra');
    const source = './data';
    const destination = './backup';
    
    // Ensure the backup directory exists
    async function backup() {
      try {
        await fs.ensureDir(destination);
        console.log('Backup directory ensured.');

        await fs.copy(source, destination);
        console.log('Files successfully backed up.');
      } catch (err) {
        console.error('Error during backup:', err);
      }
    }

    backup();

    // Removing old backups
    async function removeBackup() {
      try {
        await fs.remove(destination);
        console.log('Old backup removed.');
      } catch (err) {
        console.error('Error removing old backup:', err);
      }
    }

    removeBackup();
  

In this example, the script first ensures that the backup directory exists. Then it
copies the contents of the source directory to the backup directory. Lastly, it
demonstrates how to remove old backups.

By utilizing `fs-extra`, developers can make file system operations much more
straightforward and error-free.

Hash: baa7356b4f0c2575dee44bd5f6d501229f80ea3a4d3bcaa5e3d2a118df6bd4ee

Leave a Reply

Your email address will not be published. Required fields are marked *