Making and Removing Directories

At times you may need to implement a directory structure for files being stored by your Node.js application. The fs module provides the functionality to add and remove directories as necessary.

To add a directory from Node.js, use one of the following fs calls:

fs.mkdir(path, [mode], callback)
fs.mkdirSync(path, [mode])

The path can be absolute or relative. The optional mode parameter allows you to specify the access mode for the new directory.

The mkdirSync(path) function returns true or false, depending on whether the directory was successfully created. On the other hand, an asynchronous mkdir() call passes an error value to the callback function if an error is encountered when creating the directory.

You should keep in mind that when using the asynchronous method, you need to wait for the callback for the creation of the directory before creating a subdirectory in that directory. The following code snippet shows how to chain together the creation of a subdirectory structure:

fs.mkdir("./data", function(err){
  fs.mkdir("./data/folderA", function(err){
    fs.mkdir("./data/folderA/folderB", function(err){
      fs.mkdir("./data/folderA/folderB/folderD", function(err){
      });
    });
    fs.mkdir("./data/folderA/folderC", function(err){
      fs.mkdir("./data/folderA/folderC/folderE", function(err){
      });
    });
  });
});

To delete a directory from Node.js, use one of the following fs calls, with either an absolute or relative path:

fs.rmdir(path, callback)
fs.rmdirSync(path)

The rmdirSync(path) function returns true or false, depending on whether the directory was successfully deleted. On the other hand, an asynchronous rmdir() call passes an error value to the callback function if an error is encountered when deleting the directory.

Just as with the mkdir() calls, you should keep in mind that when using the asynchronous method, you need to wait for the callback of the deletion of the directory before deleting the parent directory. The following code snippet shows how to chain together the deletion of a subdirectory structure:

fs.rmdir("./data/folderA/folderB/folderD", function(err){
  fs.rmdir("./data/folderA/folderB", function(err){
    fs.rmdir("./data/folderA/folderC/folderE", function(err){
      fs.rmdir("./data/folderA/folderC", function(err){
        fs.rmdir("./data/folderA", function(err){
        });
      });
    });
  });
});

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.185.69