Node.js implements batch removal of BOM file headers

  • 2020-05-07 19:14:49
  • OfStack

The former colleague wrote a tool, but there is bug, which means the format of the original file is changed to utf8 BOM after replacing the file. This XML with BOM may not be able to be read out under Mac, so we need to write a tool to handle 1.

In fact, the idea is relatively simple, first traverse the directory, and then read the directory, the first 3 bytes of the file to remove, and then save the utf-8 format of the file can be directly on the code :)


var fs = require('fs');
var path = " The target 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 Read directory: \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('\ found BOM File: ', filePath, "\n");                     buff = buff.slice(3);
                    fs.writeFile(filePath, buff.toString(), "utf8");
                }
            }
        });            } else {
        console.log('Not Found Path : ', dirPath);
    }
} readDirectory(path);


Related articles: