Node.js an open-source and multi-platform server framework, which uses javascript on the server and user asynchronous programming, which makes it very useful. Renaming number of files is very hectic and boring process, but all thanks node’s async programming, which makes this process very easy. we will learn How to rename files using Node.js
Consider you have a bunch of mp3 files to rename to lowercase or according to your personal branding etc, Renaming one by one is not an option, so we will use Node.js to do this process. Let’s see How we can achieve it :).
The things you need to understand:
- Name of old files
- Path of old files
- Name of new files
- Path of new files
You need above four parameters to do this task.
First, we will do this task by using Node.js File System Module
Article Contents
How TO Rename files using Node.js Asynchronously
Syntax : fs.rename(oldPath, newPath, callbackFunction)
code:
const path = require("path"); const fs = require('fs'); fs.rename('/file/oldfilename.png', '/file/path/new-name.png', function(err) { if (err) { console.log('ERROR: ' + err); throw err; } console.log('File renamed Succesffulyy!!'); });
The asynchronous approach can generate an error, please avoid it as much as you can. In the above code, we are passing an old name and a new name with file paths, The fs.rename() Method will d the task of renaming.If you want to repeat it for multiple files you can use forEach function.
How TO Rename files using Node.js synchronously
Syntax : fs.rename(oldPath, newPath)
Code:
const path = require("path"); const fs = require('fs'); fs.renameSync('/file/oldfilename.png', '/file/path/new-name.png'); //for multiple files you can use forEach Loop or for loop
The synchronous approach is best and guarantees, that your files will be renamed synchronously. In the fs.renameSync() function you need to pass two parameters old name and the new name with respective file paths.for rename all the files in the directory you can use forEach function to do the task.
How TO Rename files using Node.js and RegExp
You can also achieve this by using RegExp with Node.js, here we will read the files directory synchronously and then use RegExp and fs.rename function to rename files.
const fs = require('fs'); const path = require('path'); var args = process.argv.slice(2); var dir = args[0]; var match = RegExp(args[1], 'g'); var replace = args[2]; var files; //reading the dir files = fs.readdirSync(dir); files.filter(function(file) { return file.match(match); }).forEach(function(file) { var filePath = path.join(dir, file), newFilePath = path.join(dir, file.replace(match, replace)); //using fs.rename function to rename files fs.renameSync(filePath, newFilePath); });
There is also a Module on NPM called Renamer, you can also check that https://www.npmjs.com/package/renamer, which gives lot options to do renaming task.