首頁 > web前端 > js教程 > 主體

Node.js檔案編碼格式轉換步驟詳解

php中世界最好的语言
發布: 2018-05-15 10:53:50
原創
1460 人瀏覽過

這次帶給大家Node.js檔案編碼格式轉換步驟詳解,Node.js檔案編碼格式轉換的注意事項有哪些,下面就是實戰案例,一起來看一下。

專案很多 lua 檔案不是 utf-8格式,使用 EditPlus 查看的時候,顯示為ASCII。還有的是帶BOM的,帶BOM倒好處理,之前寫過,有一定規律。

ASCII編碼就比較蛋疼,透過搜尋網路資源,反覆測試對比,最終形成下面比較可靠的方法(有一些EditPlus顯示編碼為utf-8但node.js庫返回的卻是其它編碼>_<)

判斷修改是否無誤,只需要在修改完之後,透過SVN提交,瀏覽提交列表,雙擊任意一項待提交文件,如果顯示下圖所示的對話框,則說明修改成功,其它都會看到中文反而變成亂碼了

var fs = require('fs');
var chardet = require('chardet');
var jschardet = require("jschardet");
var encoding = require("encoding");
var path = "lua目录";
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() && /\.lua$/.test(filePath)) {
        var buff = fs.readFileSync(filePath);
        if (buff.length && 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");
        }
        // { encoding: 'UTF-8', confidence: 0.99 }
        // var charset = chardet.detectFileSync(filePath);
        var info = jschardet.detect(buff);
        if (info.encoding == "GB2312" || info.encoding == "ascii") {
          var resultBuffer = encoding.convert(buff, "UTF-8", info.encoding);
          fs.writeFile(filePath, resultBuffer, "utf8");
        }
        else if (info.encoding != "UTF-8" && chardet.detectFileSync(filePath) != "UTF-8")
        {
          if (buff.toString().indexOf("\r\n") > -1)
          {
            var resultBuffer = encoding.convert(buff, "UTF-8", "GBK");
            fs.writeFile(filePath, resultBuffer, "utf8");
          }
        }
      }
    });
  } else {
    console.log('Not Found Path : ', dirPath);
  }
}
readDirectory(path);

注意上面的判斷,第一個明確是G​​B2312或者ascii時,直接將相應的編碼轉為utf-8。而如果返回是格式,先判斷是否有PC下的換行符,如果有則全部將它視為GBK進行處理。

整個想法其實是比較簡單,難度在於如果判斷文件編碼格式。這個真的很難>_<,取得原編碼格式後,呼叫 encoding.convert(buff, 目標編碼格式 , 原始編碼格式 ); 可得到所需的編碼。如果有空而且有興趣,可以下載Notepad 的源碼,看看它是如何判斷文件的編碼格式

註:上面的方法所修改的文件,跟Mac 上需要提交的文件列表是一致的,至少能解決我目前遇到的問題。如果有特殊的,可對上面的程式碼進行修正。

用到的第三方函式庫:

encoding https://github.com/andris9/encoding
jschardet https://github.com/aadsm /jschardet
node-chardet https://github.com/runk/node-chardet

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

Vue實作PopupWindow元件使用步驟解析

vue jquery lodash滑動時頂部懸浮固定功能實現詳解

以上是Node.js檔案編碼格式轉換步驟詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!