栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

Node.js实现批量去除BOM文件头

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Node.js实现批量去除BOM文件头

之前的同事写了一个工具,但有bug,就是在替换文件后原文件的格式变成utf8 BOM了,这种带BOM的XML在Mac下可能读取不出来,所以就需要写个工具处理一下。

其实思路比较简单,首先遍历目录,然后读取目录,将文件头三个字节去除掉,然后保存为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('发现BOM文件:', filePath, "n");

                    buff = buff.slice(3);
                    fs.writeFile(filePath, buff.toString(), "utf8");
                }
            }
        });       

    } else {
        console.log('Not Found Path : ', dirPath);
    }
}

readDirectory(path);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/105013.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号