製作離線手冊時遇到一整批文件開啟後是亂碼,追查發現檔案編碼不是 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);
file_type 是白名單機制,只有列在裡面的副檔名才會被處理,可以借此避開圖片、CSS 等非文字檔。writeFile 的 callback 改成 Promise 並搭配 Promise.all,或直接用同步 API,避免大量非同步寫入同時進行。