Renaming files using node.js
Asked Answered
P

6

141

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.

Pfennig answered 19/3, 2014 at 11:35 Comment(0)
D
231

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

Dorr answered 19/3, 2014 at 11:41 Comment(7)
last 2 lines of your answer are very important :)Sawbuck
you can just import .json: const obj = require('/path/to/countries.json'); and then: for(var p in obj) {...}Crownpiece
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.Dorr
It is safer to use path.resolve instead of concatenating your path string.Sponger
For synchronous version fs.renameSync(oldPath, newPath);Alleneallentown
@Dorr 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: github.com/nodejs/node/blob/…Valois
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.Dorr
Y
31

For synchronous renaming use fs.renameSync

fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');
Yolk answered 14/5, 2019 at 12:57 Comment(0)
S
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)

Sawbuck answered 19/3, 2014 at 11:42 Comment(0)
M
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!

Maldon answered 8/12, 2016 at 1:54 Comment(2)
Is there a reason why this would be preferred over fs.rename?Sharpe
It's synchronous - But could use nodejs.org/api/fs.html#fs_fs_renamesync_oldpath_newpathYolk
A
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

Ask answered 25/10, 2023 at 17:11 Comment(0)
G
-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.

Gunther answered 16/1, 2023 at 15:51 Comment(1)
Pretty rich to assume the paths will be windows-only. Also in the current year there is a promisified version of rename().Infanticide

© 2022 - 2024 — McMap. All rights reserved.