When programming, using modules and libraries within our code is a must. As the libraries are written by others, beginners will be confused on what each function and the arguments mean. Throughout this post, we will go through renaming files with Node.js.
First, we must grasp the concept of opening a file, so the program knows what file to search for. The following is a simple set of code that will open a file.
Let's go through what each part of the code represents.
First, we must grasp the concept of opening a file, so the program knows what file to search for. The following is a simple set of code that will open a file.
Open()
const fs = require('fs');
fs.open('/open/some/file.txt', 'r', (err, fd) => {
if (err) {
throw err;
}
fs.close(fd, (err) => {
if (err) {
throw err;
}
});
});
- fs is a module that allows access to a physical file system.
- fd represents the file descriptor, which is used for accessing newly opened files.
Rename()
Now that you understand how to open a simple file, let's get into how to rename a file. In Node.js, there is a built in module that allows you to do this easily:fs.rename(oldPath, newPath, callback){
Here is an example of how the code can be used.fs.rename('oldFile.txt', 'newFile.txt', (err) => {
if (err) {
throw err;
}
console.log('Rename complete!');
});
Let's go through what each part of the function represents. - oldPath represents the current name of the file/directory
- newPath represents the name of the file you want to rename it to
- callback can be used to throw an error, if there is one
You can see that this module uses fs in front of the rename() function. This goes back to the first part, opening a file. Remember that fs is the prefix before using any function that uses the physical file system, as it is already declared.
Comments
Post a Comment