Heim  >  Artikel  >  Web-Frontend  >  nodejs批量修改文件编码格式_node.js

nodejs批量修改文件编码格式_node.js

WBOY
WBOYOriginal
2016-05-16 16:18:301464Durchsuche

摘要:
  最近在制作手册的时候遇到了一个问题'文档乱码',查看文件之后发现文件编码不对,总共100多个文件,如果用编辑器另存为utf8,那就悲催了。所以自己就写了个程序,批量修改文件编码格式。

代码:

复制代码 代码如下:

/**
 * 修改文件编码格式,例如:GBK转UTF8
 * 支持多级目录
 * @param {String} [root_path] [需要进行转码的文件路径]
 * @param {Array}  [file_type] [需要进行转码的文件格式,比如html文件]
 * @param {String} [from_code] [文件的编码]
 * @param {String} [to_code]   [文件的目标编码]
 */
// 引入包
var fs = require('fs'),
  iconv = require('iconv-lite');
// 全局变量
var root_path = './html',
    file_type = ['html', 'htm'],
    from_code = 'GBK',
    to_code   = 'UTF8';
/**
 * 判断元素是否在数组内
 * @date   2015-01-13
 * @param  {[String]}   elem [被查找的元素]
 * @return {[bool]}        [description]
 */
Array.prototype.inarray = function(elem) {
  "use strict";
  var l = this.length;
  while (l--) {
    if (this[l] === elem) {
      return true;
    }
  }
  return false;
};
/**
 * 转码函数
 * @date   2015-01-13
 * @param  {[String]}   root [编码文件目录]
 * @return {[type]}        [description]
 */
function encodeFiles(root) {
  "use strict";
  var files = fs.readdirSync(root);
  files.forEach(function(file) {
    var pathname = root + '/' + file,
      stat = fs.lstatSync(pathname);
    if (!stat.isDirectory()) {
      var name = file.toString();
      if (!file_type.inarray(name.substring(name.lastIndexOf('.') + 1))) {
        return;
      }
      fs.writeFile(pathname, iconv.decode(fs.readFileSync(pathname), from_code), {
        encoding: to_code
      }, function(err) {
        if (err) {
          throw err;
        }
      });
    } else {
      encodeFiles(pathname);
    }
  });
}
encodeFiles(root_path);

 

小结:
  上面的程序支持多级目录,同一个文件不能进行多次操作,否则又会出现乱码。

完整代码:https://github.com/baixuexiyang/coding,你可以fork到自己的账号下,如果有bug请在issue上提。

是不是非常不错呢,希望大家能够喜欢,有疑问就留言吧。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn