信息发布→ 登录 注册 退出

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

发布时间:2026-01-11

点击量:

之前的同事写了一个工具,但有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);

标签:# path  # bug  # file  # XML  # BOM  # fs  # existsSync  # nbsp  # dirPath  # forEach  # readdirSync  # files  # Node.js  # readDirectory  # function  # require  # 不出来  # 就是在  # 保存为  # 写了  # 遍历  # Node.js文本文件BOM头的去除方法  # 批量去除BOM文件头  
在线客服
服务热线

服务热线

4008888355

微信咨询
二维码
返回顶部
×二维码

截屏,微信识别二维码

打开微信

微信号已复制,请打开微信添加咨询详情!