摘要:
最近在制作手冊的時候遇到了一個問題'文檔亂碼',查看文件之后發現文件編碼不對,總共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上提。
