SoFunction
Updated on 2025-03-10

Example of usage of Nodejs using the fs-extra module for directory and file operations

Preface

Infs-extraModule isfsThe module extension provides some additional functions to make the operation of files and directories more convenient. So how do we use the fs-extra module for directory and file operations? Here are some common usage examples:

1. ensureDir/ensureDirSync - Create directory

ensureDirMethod is used to see if the directory exists, and if it does not exist, create one.

const fs = require('fs-extra');
const dir = '/Users/tal/Library/Application Support';

(dir, function (err) {
  if (err) {
    (err);
  } else {
    ('Directory created successfully!');
  }
});

2. ensureFile/ensureFileSync - Create a file

ensureFileMethod is used to see if the file exists, and if it does not exist, create one.

const fs = require('fs-extra');
const file = '/Users/tal/Library/Application Support/';

(file, function (err) {
  if (err) {
    (err);
  } else {
    ('File created successfully!');
  }
});

3. emptyDir/emptyDirSync - Clear the directory

emptyDirThe method is used to clear all folders and files in a directory. If the directory does not exist, create one.

const fs = require('fs-extra');
const dir = '/Users/tal/Library/Application Support';

(dir, function (err) {
  if (err) {
    (err);
  } else {
    ('Directory emptied successfully!');
  }
});

These methods provide a more convenient and secure way to operate files and directories without having to write complex logic manually.fs-extraThese functions of modules are very useful for file system management.

Attachment: Delete files, directories

remove(dir, callback)

Example:

var fs = require('fs-extra')
 
('/tmp/myfile', function(err) {
  if (err) return (err)
 
  ("success!")
})
 
('/home/jprichardson')

Summarize

This is the article about Nodejs using the fs-extra module for directory and file operations. For more related Nodejs directory and file operations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!