programing

Renaming files using node.js

magicmemo 2023. 9. 8. 21:22
반응형

Renaming files using node.js

다른 국가 이름을 가진 260.png 파일이 있는 폴더가 있습니다.Afghanistan.png,Albania.png,Algeria.png,기타.

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",  
  ...  
}

.png 파일 이름을 소문자로 변경하고 싶습니다.그것은 나의 폴더에 다음과 같은 입력을 하고싶다는 것을 의미합니다..png이미지:af.png,al.png,dz.png,기타.

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.

사용해야 합니다.fs이 경우: http://nodejs.org/api/fs.html

그리고 특히.fs.rename()함수:

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);
        });
    }
});

(이것은 여기서 당신이.json파일을 신뢰할 수 있으며 파일 이름에 키와 값을 직접 사용해도 안전합니다.만약 그렇지 않다면, 반드시 제대로 탈출하세요!)

For synchronous renaming use fs.renameSync

fs.renameSync('/path/to/Afghanistan.png', '/path/to/AF.png');
  1. fs.readdir(path, callback)
  2. fs.rename(old,new,callback)

통과하다http://nodejs.org/api/fs.html

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

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!

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.

ReferenceURL : https://stackoverflow.com/questions/22504566/renaming-files-using-node-js

반응형