Renaming files using Node.js

Originally published by Nick Major at https://coderrocketfuel.com

Introduction

Are you working with system files in Node.js and need an easy way to rename files in a programmatic manner?

Luckily, Node.js has a built-in way to do this with their File System (Fs) core module, which has both a fs.rename() and fs.renameSync() method to give a file a new name.

Both functions will give you the same end result but go about doing it in a little different way. The synchronous fs.renameSync() version will stop your code and wait until the file has been successfully renamed or an error has occurred to continue running. And the asynchronous version fs.rename() will not block your code and return a callback function when the file is removed instead.

We'll show you how to use both of the methods.

For the code below to work, make sure you have Node.js installed and a file you want to rename placed in the root of your project directory. In this example, our file is a PNG image file named "your-file.png". But the rename methods will work on any filetype.

First, let's cover the fs.rename() version. We'll give you the full code and then explain all the different parts afterward:

fs.rename():

const fs = require("fs")
const path = require("path")
 
const pathToFile = path.join(__dirname, "your-file.png")
const newPathToFile = path.join(__dirname, "new-filename.png")
 
fs.rename(pathToFile, newPathToFile, function(err) {
  if (err) {
    throw err
  } else {
    console.log("Successfully renamed the file!")
  }
})

Let's break down each part of the code:

  1. First, we import the Fs module and Path core modules.
  2. Next, we create the pathToFile and newPathToFile variables. We use the Path module to get the current path of our file we want to change. And we also create a path with the name that we want our new file to have.
  3. Then, we use the fs.rename() function. We pass both file paths to the function and it returns a callback.
  4. Inside the callback function, we do some error handling and then, if successful, we console.log() a success message.

When you run the code in your terminal, you should see this output:

$ Successfully renamed the file!

If you look in the directory where the file is located, you should see that the file in question has a new name.

Now let's cover the synchronous version!

fs.renameSync():

const fs = require("fs")
const path = require("path")
 
const pathToFile = path.join(__dirname, "your-file.png")
const newPathToFile = path.join(__dirname, "new-filename.png")
 
try {
  fs.renameSync(pathToFile, newPathToFile)
  console.log("Successfully renamed the file!")
} catch(err) {
  throw err
}

Similar to the previous example, we require both the Fs and Path core modules. Then, we get the path to the current file and create a path with what we want the new name to be.

But then we use a try...catch statement. In the try section, we pass both the pathToFile and newPathToFile variables to the fs.renameSync() function and log a success message when the file has successfully been renamed. And we use the catch section to throw any errors that may occur along the way.

When you run the code in your terminal, you should see the same output as before:

$ Successfully renamed the file!

And the file in your directory will have a new name.

Conclusion

Hopefully, this was helpful in your work with system files and Node.js.

Node.js's File System (Fs) core module has a ton of other useful methods. Check out their documentation for more information.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Best 50 Nodejs interview questions from Beginners to Advanced in 2019

Node.js 12: The future of server-side JavaScript

An Introduction to Node.js Design Patterns

Basic Server Side Rendering with Vue.js and Express

Fullstack Vue App with MongoDB, Express.js and Node.js

How to create a full stack React/Express/MongoDB app using Docker


#node-js #javascript #web-development

Renaming files using Node.js
60.30 GEEK