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

js教程评论344 views阅读模式

这篇文章主要介绍了Node.js实现批量去除BOM文件头,本文直接给出实现代码,需要的朋友可以参考下。

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

其实思路比较简单,首先遍历目录,然后读取目录,将文件头三个字节去除掉,然后保存为utf-8格式的文件即可,直接上代码吧 Node.js实现批量去除BOM文件头

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读取目录: ', 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);

以上就是本章的全部内容,更多相关教程请访问Node.js视频教程!

企鹅博客
  • 本文由 发表于 2020年6月7日 17:58:18
  • 转载请务必保留本文链接:https://www.qieseo.com/416130.html

发表评论