javascript批量修改檔案編碼格式的方法_javascript技巧

來源:互聯網
上載者:User

本文執行個體講述了javascript批量修改檔案編碼格式的方法。分享給大家供大家參考。具體如下:

摘要:

最近在製作手冊的時候遇到了一個問題'文檔亂碼',查看檔案之後發現檔案編碼不對,總共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);

小結:

上面的程式支援多級目錄,同一個檔案不能進行多次操作,否則又會出現亂碼。
完整代碼可點擊此處本站下載。

希望本文所述對大家的javascript程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.