Search code examples
javascriptnode.jsglob

I want to rename a particular string in multiple filenames in nodejs


I want to rename a particular string in filenames. I am using glob and path to extract multiple file names from multiple locations. Now I just want to rename those files like abcd-change-name.js to abcd-name-changed.js

Here's what I have done so far

 var glob = require("glob")
 var path = require('path')
 const fs = require('fs')

 glob(process.cwd() + "/directory/**/*-change-name*.js", {}, function (er, 
 files) {
  for(i=0; i<files.length; i++){
     var f = path.basename(files[i])
     var d = path.dirname(files[i])
     fs.renameSync(files[i] , d + '/name-changed.js', function (err) {
        if (err) throw err;
        console.log('renamed complete');
      });
  }
 })

The code is changing all the files with the js extension to name-changed.js in their respective folders.


Solution

  • Your code uses has the line fs.renameSync(files[i], d + '/name-changed.js', ... but this line of code renames files[i] to '[foldername]/name-changed.js'.

    I would suggest having something like fs.renameSync(files[i], files[i].replace('change-name', 'name-changed'), ...

    In other words, you have told fs to rename the file to have a filename of 'name-changed.js' but you want it to contain the original filename data but with 'change-name' replaced with 'name-changed'.

    Here is a full code example based on your code.

     var glob = require("glob")
     var path = require('path')
     const fs = require('fs')
    
     glob(process.cwd() + "/directory/**/*-change-name*.js", {}, function (er, 
     files) {
      for(i=0; i<files.length; i++){
         var f = path.basename(files[i])
         var d = path.dirname(files[i])
         fs.renameSync(files[i] , files[i].replace('change-name', 'name-changed'), function (err) {
            if (err) throw err;
            console.log('renamed complete');
          });
      }
     })