先前同事寫了一個工具,但留下了一個 bug:檔案替換之後,原檔案的編碼變成了 UTF-8 with BOM。這種帶 BOM 的 XML 在 Mac 環境下有可能讀取不出來,於是就得自己寫一支小工具來善後。
流程其實很直觀:先遞迴遍歷目錄,逐個讀取檔案,判斷開頭三個位元組是否為 BOM 標記(EF BB BF),若是就把它去掉,再以 UTF-8 重新寫回。
var fs = require('fs');
var path = "目標路徑..";
function readDirectory(dirPath) {
if (fs.existsSync(dirPath)) {
var files = fs.readdirSync(dirPath);
files.forEach(function(file) {
var filePath = dirPath + "/" + file;
var stats = fs.statSync(filePath);
if (stats.isDirectory()) {
console.log('\n讀取目錄:\n', filePath, "\n");
readDirectory(filePath);
} else if (stats.isFile()) {
var buff = fs.readFileSync(filePath);
if (buff[0].toString(16).toLowerCase() == "ef" &&
buff[1].toString(16).toLowerCase() == "bb" &&
buff[2].toString(16).toLowerCase() == "bf") {
//EF BB BF 239 187 191
console.log('\n發現BOM文件:', filePath, "\n");
buff = buff.slice(3);
fs.writeFile(filePath, buff.toString(), "utf8");
}
}
});
} else {
console.log('Not Found Path : ', dirPath);
}
}
readDirectory(path);
這支腳本可用,但有幾處在正式環境中建議調整。
用 slice(3) 之後轉字串再寫回,有編碼風險。buff.toString() 預設就是 UTF-8,對純文字檔沒問題;但若目標資料夾裡混有圖片或其他二進位檔案,這個寫法會破壞它們。建議只針對特定副檔名(如 .xml)處理,或改用 fs.writeFileSync(filePath, buff) 直接寫入 Buffer,避免任何解碼再編碼的過程。
同步 API 的效能問題。這裡全部使用 readFileSync、statSync、writeFileSync。腳本規模小時沒差,但檔案數量一大就會明顯變慢,而且過程中無法回報進度。改成 fs.promises 搭配 async/await 會流暢很多。
建議先 dry-run。批次修改檔案屬於不可逆操作,正式執行前最好先只印出「哪些檔案會被修改」,確認無誤後再實際寫入。另外,toString(16) 在數值小於 0x10 時不會補零,雖然 BOM 這三個位元組剛好不受影響,但養成用 buff.readUInt8(0) === 0xEF 這類寫法的習慣會更安全。
更簡潔的判斷方式其實是:
if (buff.length >= 3 && buff[0] === 0xEF && buff[1] === 0xBB && buff[2] === 0xBF) {
fs.writeFileSync(filePath, buff.slice(3));
}
這樣既準確,也不會誤傷非文字檔案。