Renaming files using Node.js

Renaming files using Node.js

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

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

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Top Node.js Development Companies and Expert NodeJS Developers

A thoroughly researched list of top NodeJS development companies with ratings & reviews to help hire the best Node.JS developers who provide development services and solutions across the world. List of Leading Node.js development Service Providers...

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.