Directories Creation and Deletion
Node.js is a popular JavaScript runtime built on Chrome's V8 JavaScript engine. It is used to build fast and scalable network applications. One of the key features of Node.js is its ability to interact with the file system on its host machine. This includes the ability to create and delete directories. In this article, we will explore how to create and delete directories using Node.js.
Introduction to Node.js File System Module
Node.js provides a built-in module called 'fs' for working with the file system on your computer. This module provides a lot of useful methods to work with directories and files. To include the 'fs' module in your Node.js application, you need to require it using the following code:
var fs = require('fs');
Creating a Directory
To create a directory in Node.js, you can use the fs.mkdir()
method. It takes two arguments: the path of the directory and a callback function. The callback function is executed when the directory is created. Here is an example:
var fs = require('fs');
fs.mkdir('myNewDirectory', function (err) {
if (err) {
console.log(err);
} else {
console.log('New directory successfully created.');
}
});
In this example, a new directory named 'myNewDirectory' is created. If the operation is successful, it will log 'New directory successfully created.' to the console. If there is an error, it will log the error message.
Deleting a Directory
To delete a directory in Node.js, you can use the fs.rmdir()
method. Similar to fs.mkdir()
, it takes the path of the directory and a callback function as arguments. The callback function is executed when the directory is deleted. Here is an example:
var fs = require('fs');
fs.rmdir('myNewDirectory', function (err) {
if (err) {
console.log(err);
} else {
console.log('Directory successfully deleted.');
}
});
In this example, the directory named 'myNewDirectory' is deleted. If the operation is successful, it will log 'Directory successfully deleted.' to the console. If there is an error, it will log the error message.
Conclusion
In this article, we learned how to create and delete directories in Node.js using the 'fs' module. We used the fs.mkdir()
method to create a directory and the fs.rmdir()
method to delete a directory. It's important to note that the fs.rmdir()
method can only delete empty directories. If the directory is not empty, you will get an error. In a future article, we will discuss how to delete non-empty directories and work with files in Node.js.