jlalovi
jlalovi

Reputation: 1473

Renaming files using node.js

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.

Upvotes: 147

Views: 191824

Answers (6)

Beraliv
Beraliv

Reputation: 564

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

Upvotes: 0

SURAJ CHAKRAWARTI
SURAJ CHAKRAWARTI

Reputation: 43

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.

Upvotes: -3

Ole
Ole

Reputation: 47088

For synchronous renaming use fs.renameSync

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

Upvotes: 34

VoteyDisciple
VoteyDisciple

Reputation: 37813

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

Upvotes: 238

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93411

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!

Upvotes: 5

Pranav
Pranav

Reputation: 2172

  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)

Upvotes: 8

Related Questions