批量转码(从GBK到UTF-8)

因为公司业务的历史原因,我们公司是默认采用gbk编码格式的,由此带来很多淡疼的问题,有相同经历的人肯定可以理解

特别是在前端工程化逐渐发展壮大的今天,很多工具编译出来的文件都是默认utf8格式的。

于是实在忍受不了,只得各种查阅借鉴,自己动手写一个批量转换的nodejs的脚本,同时也可以学习一下nodejs的用法

毕竟程序就是为了效率服务呀

const path = require('path');
const util = require('util');
const fs = require('fs');
const iconvLite = require('iconv-lite');

//全局
const   entry = './script',  //入口路径
        dist = './script/utf8', //输出路径
        from_code = 'GBK',
        target_code = 'UTF8';

var target = '';
       
function run(folderPath,targetPath){
    folderPath = path.join(__dirname,folderPath);
    target = path.join(__dirname,targetPath);
    if(!fs.existsSync(folderPath)){ //判断文件夹是否存在
        throw new Error('输入路径不存在')
    };
    if(!fs.existsSync(target)){
        fs.mkdir(target);
    };
    var files = fs.readdirSync(folderPath); //获取目录下所有文件列表
    files.forEach(filename => {
        var filepath = path.join(folderPath,filename);
        var stats = fs.statSync(filepath); //同步的start,作用是获取文件信息
        if(stats.isFile()){ //是否为文件
            var ext = path.extname(filepath).toLowerCase(); //返回路径文件扩展名
            if(['.js'].includes(ext)){ 
                convertToUtf8(filepath,filename)
            }
        };
    });
};

function convertToUtf8(fileName,fname){
    var byte = fs.readFileSync(fileName);
    if(byte[0] == 0xef && byte[1]==0xbb || byte[0] == 0xfe && byte[1] == 0xff || byte[0] == 0xff && byte[1] == 0xfe){
        //已经是utf8不做转换
        return;
    };
    byte = iconvLite.decode(byte,from_code); //按gbk读取之后转换为utf8才不会乱码
    var content = "ufeff" + byte.toString(target_code); //标记bom-utf8
    fs.writeFileSync(target+'/'+fname,content);
    
}


run(entry,dist);

  

原文地址:https://www.cnblogs.com/antelope/p/8443366.html