136

I have a folder with 260 .png files with different country names: Afghanistan.png, Albania.png, Algeria.png, etc.

I have a .json file with a piece of code with all the ISO codes for each country like this:

{  
  "AF" : "Afghanistan",  
  "AL" : "Albania",  
  "DZ" : "Algeria",  
  ...  
}

I would like to rename the .png files with their ISO name in low-case. That means I would like to have the following input in my folder with all the .png images: af.png, al.png, dz.png, etc.

I was trying to research by myself how to do this with node.js, but I am a little lost here and I would appreciate some clues a lot.

starball
  • 20,030
  • 7
  • 43
  • 238
jlalovi
  • 1,363
  • 2
  • 8
  • 6

5 Answers5

223

You'll need to use fs for that: http://nodejs.org/api/fs.html

And in particular the fs.rename() function:

var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
    if ( err ) console.log('ERROR: ' + err);
});

Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.

fs.readFile('/path/to/countries.json', function(error, data) {
    if (error) {
        console.log(error);
        return;
    }

    var obj = JSON.parse(data);
    for(var p in obj) {
        fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    }
});

(This assumes here that your .json file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)

hughc
  • 79
  • 9
VoteyDisciple
  • 37,319
  • 5
  • 97
  • 97
  • 11
    last 2 lines of your answer are very important :) – Pranav Mar 19 '14 at 11:47
  • you can just import .json: `const obj = require('/path/to/countries.json');` and then: `for(var p in obj) {...}` – ViES Sep 16 '18 at 01:47
  • 3
    You could, but... don't. Using `require` ***executes code*** in that file. You're introducing a way for someone to potentially inject malicious code into the application (i.e., by modifying the .json file). Reading and using `JSON.parse()` avoids that altogether. Don't compromise security for the sake of writing very slightly less code. – VoteyDisciple Sep 16 '18 at 10:40
  • It is safer to use [path.resolve](https://nodejs.org/api/path.html#path_path_resolve_paths) instead of concatenating your path string. – JulianSoto Sep 28 '18 at 03:00
  • 1
    For synchronous version `fs.renameSync(oldPath, newPath);` – Tim Apr 30 '19 at 17:38
  • @VoteyDisciple I'm wondering where you got your info regarding `require` executing JSON code. as far as I could understand the `require` source code, it just reads the file contents and runs `JSON.parse` on it: https://github.com/nodejs/node/blob/05002373176e8758c8c604f06659e171de4ca902/lib/internal/modules/cjs/loader.js#L737 – gilad905 Dec 28 '22 at 10:05
  • This answer is from 8.5 years ago. It could be that in 2022 it's perfectly reasonable to just `require()` to get your JSON—I don't know. Personally I'd still write out the `.parse()` for the sake of clarity, rather than trusting the reader to know and remember that `require()` has specialized behavior for .json files. – VoteyDisciple Dec 28 '22 at 15:41
27

For synchronous renaming use fs.renameSync

fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');
Ole
  • 41,793
  • 59
  • 191
  • 359
8
  1. fs.readdir(path, callback)
  2. fs.rename(old,new,callback)

Go through http://nodejs.org/api/fs.html

One important thing - you can use sync functions also. (It will work like C program)

Pranav
  • 2,054
  • 4
  • 27
  • 34
5

For linux/unix OS, you can use the shell syntax

const shell = require('child_process').execSync ; 

const currentPath= `/path/to/name.png`;
const newPath= `/path/to/another_name.png`;

shell(`mv ${currentPath} ${newPath}`);

That's it!

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
-2

Here's an updated version of the script that renames a file of any directory; i.e => "C:\Users\user\Downloads"

const fs = require('fs');

// current file name
const fileName = 'C:\\Users\\user\\Downloads\\oldFileName.jpg';

// new file name
const newFileName = 'C:\\Users\\user\\Downloads\\newFileName.jpg';

fs.rename(fileName, newFileName, function(err) {
    if (err) throw err;
    console.log('File Renamed!');
});

This script renames a file with a specific path and file name, in this case, "C:\Users\user\Downloads\oldFileName.jpg" to "C:\Users\user\Downloads\newFileName.jpg" using the "fs" module in Node.js. The "rename" function takes in the current file name, the new file name, and a callback function that will be called after the file has been renamed. If there is an error, it will throw an error. Otherwise, it will print "File Renamed!" to the console.

  • Pretty rich to assume the paths will be windows-only. Also in the current year there is a [promisified version of `rename()`](https://nodejs.org/api/fs.html#fspromisesrenameoldpath-newpath). – Biller Builder Jan 30 '23 at 19:10