欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Node.js文件编码格式的转换的方法

程序员文章站 2023-01-28 18:52:35
项目很多 lua 文件不是 utf-8格式,使用 editplus 查看的时候,显示为ascii。还有的是带bom的,带bom倒好处理,之前写过,有一定规律。 ascii...

项目很多 lua 文件不是 utf-8格式,使用 editplus 查看的时候,显示为ascii。还有的是带bom的,带bom倒好处理,之前写过,有一定规律。

ascii编码就比较蛋疼,通过搜索网上资源,反复测试对比,最终形成下面比较靠谱的方法(有一些 editplus显示编码为utf-8但node.js库返回的却是其它编码>_<)

判断修改是否无误,只需要在修改完之后,通过svn提交,浏览提交列表,双击任意一项待提交文件,如果显示下图所示的对话框,则说明修改成功,其它都会看到中文反而变成乱码了

Node.js文件编码格式的转换的方法

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

注意上面的判断,第一个明确是 gb2312或者ascii时,直接将相应的编码转为 utf-8。而如果返回是格式,先判断是否有pc下的换行符,如果有则全部将它视为gbk进行处理。

整个思路其实是比较简单,难点在于如果判断文件编码格式。这个真的很难>_<,获取原编码格式后,调用 encoding.convert(buff, 目标编码格式 , 原始编码格式 ); 便可得到所需要的编码。如果有空而且有兴趣,可以下载notepad++的源码,看它是如何判断文件的编码格式

注:上面的方法所修改的文件,跟 mac 上需要提交的文件列表是一致的,至少能解决我目前遇到的问题。如果有特殊的,可对上面的代码进行修正。

用到的第三方库:

encoding
jschardet
node-chardet

编码相关的基础知识,可以参考这篇文章:

*和其它资料太过专业化了,而且对 ascii 编码的介绍不多,不再一一列举出来了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。