zoukankan      html  css  js  c++  java
  • 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(' 读取目录: ', filePath, " ");
    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, " ");

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

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

    readDirectory(path);

  • 相关阅读:
    操作标签的属性和属性值 table表格
    dom基本获取 标签文本操作
    延时器 清除延时器
    倒计时
    电子时钟
    时间戳
    设定时间的方法
    内置对象Date
    对象的基本特点
    终于有人把云计算、大数据和 AI 讲明白了【深度好文】
  • 原文地址:https://www.cnblogs.com/meteoric_cry/p/3626964.html
Copyright © 2011-2022 走看看