node重命名文件名,使用node.js重命名文件

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!

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值