Renaming files using node.js

Javascriptnode.jsRename

Javascript Problem Overview


I am quite new in using JS, so I will try to be as specific as I can :)

  • 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.

Thanks in advance!

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

For synchronous renaming use fs.renameSync

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

Solution 3 - Javascript

  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)

Solution 4 - Javascript

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjlaloviView Question on Stackoverflow
Solution 1 - JavascriptVoteyDiscipleView Answer on Stackoverflow
Solution 2 - JavascriptOleView Answer on Stackoverflow
Solution 3 - JavascriptPranavView Answer on Stackoverflow
Solution 4 - JavascriptAbdennour TOUMIView Answer on Stackoverflow