148

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.

6 Answers 6

239

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!)

Sign up to request clarification or add additional context in comments.

7 Comments

last 2 lines of your answer are very important :)
you can just import .json: const obj = require('/path/to/countries.json'); and then: for(var p in obj) {...}
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.
It is safer to use path.resolve instead of concatenating your path string.
For synchronous version fs.renameSync(oldPath, newPath);
|
34

For synchronous renaming use fs.renameSync

fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');

Comments

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)

Comments

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!

2 Comments

Is there a reason why this would be preferred over fs.rename?
0

VoteyDisciple's answer is exhaustive, but if you're looking for a solution with Promises, you still can use fs.rename but wrapped with util.promisify:

import fs from "fs";
import util from "util";

const rename = util.promisify(fs.rename);

You can achieve the same thing using fsPromises.rename:

import {rename} from "fs/promises";

Example of how to use this function now:

try {
    await rename('/path/to/Afghanistan.png', '/path/to/AF.png');
} catch (err) {
    console.error(err);
}

Hope it helps

Comments

-3

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.

1 Comment

Pretty rich to assume the paths will be windows-only. Also in the current year there is a promisified version of rename().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.