Rename a file in Node.js using fs (File System) module - rename

Rename a file in Node.js using fs (File System) module

The fs module provides an API for interacting with the file system in a manner closely modeled around standard POSIX functions. It provides a lot of very useful functionality to access and interact with the file system. There is no need to install it because it is a part of the Node.js core. The fs module is responsible for all the asynchronous or synchronous file I/O operations.

To rename a file in Node.js we will use the rename method of the fs module. It supports both synchronous and asynchronous methods. In the following example we create a simple server in order to test our app. So after getting a request we call the rename method and return either the file is renamed or not.

1 Asynchronous usage of rename in Node.js

const http = require("http");
var fs = require('fs');

const port = process.env.PORT || "3100";

const server = http.createServer(function (req, res) {
  //set content type
  res.writeHead(200, {"Content-Type": "text/html"});

  fs.rename('old_name.txt', 'new_name.txt', (err) => {
    if (err){
      // Handle the error
      if(err.code=='ENOENT'){
        res.write("File not found")
      }else{
        res.write("An error occured")
      }
    }else{
      // File successfully renamed
      res.write("successfully renamed")
    }

    // End the response
    res.end();
  });

}).listen(port);

2 Synchronous usage of rename in Node.js

const http = require("http");
var fs = require('fs');

const port = process.env.PORT || "3100";

const server = http.createServer(function (req, res) {

  //set content type
  res.writeHead(200, {"Content-Type": "text/html"});

  try {

    // Rename file
    fs.renameSync('old_name.txt', 'new_name.txt');
    res.write("successfully renamed");

  } catch (err) {

    // Handle the error
    if(err.code=='ENOENT'){
      res.write("File not found");
    }else{
      res.write("An error occured");
    }
    
  }

  // End the response
  res.end();

}).listen(port);