DIV CSS 佈局教程網

用 Node.js 批次轉換大量檔案的編碼格式
編輯:關於JavaScript     

需求背景

製作離線手冊時遇到一整批文件開啟後是亂碼,追查發現檔案編碼不是 UTF-8。數量有一百多個,用編輯器一個一個「另存新檔」顯然不現實,於是寫了一支腳本批次處理。

實作

核心觀念很單純:用 iconv-lite 把原始位元組解碼成字串,再以目標編碼重新寫回檔案。

/**
 * 修改檔案編碼格式,例如 GBK 轉 UTF-8
 * 支援多層目錄
 * @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';

// 判斷元素是否在陣列中
Array.prototype.inarray = function(elem) {
  "use strict";
  var l = this.length;
  while (l--) {
    if (this[l] === elem) return true;
  }
  return false;
};

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

使用注意事項

  • 同一個檔案不可重複轉碼。若對已是 UTF-8 的檔案再以 GBK 解碼一次,只會產生新的亂碼,因此正式執行前建議先備份整個目錄。
  • file_type 是白名單機制,只有列在裡面的副檔名才會被處理,可以借此避開圖片、CSS 等非文字檔。
  • 來源編碼要確認清楚。實務上 GBK、GB2312、GB18030 的字元集範圍不同,遇到罕用字時以 GB18030 解碼的成功率較高。
  • 若檔案量大,可把 writeFile 的 callback 改成 Promise 並搭配 Promise.all,或直接用同步 API,避免大量非同步寫入同時進行。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved