使用node.js重命名文件 [英] Renaming files using node.js

查看:94
本文介绍了使用node.js重命名文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用JS方面还很陌生,所以我将尽我所能:)

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

  • 我有一个包含260个.png文件的文件夹,这些文件具有不同的国家/地区名称:Afghanistan.pngAlbania.pngAlgeria.png等.

我有一个.json文件,其中包含一段代码,其中包含每个国家/地区的所有ISO代码,如下所示:

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

  • 我想用小写的ISO名称重命名.png文件.这意味着我想在我的文件夹中包含所有.png图像的以下输入: af.pngal.pngdz.png
    • 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.
    • 我一直在尝试自己研究如何使用node.js进行此操作,但是我在这里有点迷失了,我会非常感激一些线索.

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

      将其循环放置在刚读取的JSON对象的键和值上,就可以得到一个批处理重命名脚本.

      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文件是可信任的,可以直接在文件名中使用其键和值是安全的.如果不是这种情况,请确保正确地转义它们!)

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

      这篇关于使用node.js重命名文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆